Why does Gson toJson always return null?

When I try to convert the base object to json, it seems to return null with everything I tried. What's wrong?

Person.java

public class Person {
    public String Name;
    public String Address;
}

Main code

Person person = new Person() {
    {
        Name = "John";
        Address = "London";
    }
};

Gson gson = new Gson();
String jsonPerson = gson.toJson(person);
+4
source share
2 answers

Gson does not support serialization of anonymous types.

See Duplicate Related Sotirios Delimanolis. Note that the double-binding initializer you used creates an anonymous subclass that has some unpleasant side effects, such as creating new classes every time you use it, and breaking things like Gson.

It will work if you created such a constructor:

class Ideone
{
    public class Person {
        public String Name;
        public String Address;

        public Person(String Name, String Address) {
            this.Name = Name;
            this.Address = Address;
        }
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Person person = new Person("John", "London");

        // System.out.println(person.Name);
        Gson gson = new Gson();
        String jsonPerson = gson.toJson(person);
    }
}

, ; .

Google Java

+7

, . TypeToken,

Type personType = new TypeToken<Person>(){}.getType();
Gson gson = new Gson();
String jsonPerson = gson.toJson(person, personType);
+1

Source: https://habr.com/ru/post/1654854/


All Articles