When I try to convert a basic object to json, it seems to return null with everything I have tried. What's wrong?
public class Person {
public String Name;
public String Address;
}
Person person = new Person() {
{
Name = "John";
Address = "London";
}
};
Gson gson = new Gson();
String jsonPerson = gson.toJson(person);
If a value is not set, it'll not be part of the resulting JSON at all. If you require that fields with null values also show up in the JSON (with null values), Gson has an option for it. But we'll look at that later.
Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls () method.
The default behavior that is implemented in Gson is that null object fields are ignored. For example, if in Employee object, we do not specify the email (i.e. email is null) then email will not be part of serialized JSON output. Gson ignores null fields because this behavior allows a more compact JSON output format. 1.
For example, if in Employee object, we do not specify the email (i.e. email is null) then email will not be part of serialized JSON output. Gson ignores null fields because this behavior allows a more compact JSON output format.
See the duplicate linked by Sotirios Delimanolis. Note that the double brace initializer you were using effectively creates an anonymous subclass, which has some nasty side effects like creating new classes every time you use it, and breaking things like Gson.
It would work if you created a constructor like this:
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);
}
}
As an aside, you should not name your fields with capital letters; begin classes with capital letters and fields with lowercase letters.
Have a look at the Google Java Style Guide for a good reference on naming conventions
The way you are instantiating your object creates an anonymous class so you loose the type. You can instead use a TypeToken
to fix this as follows
Type personType = new TypeToken<Person>(){}.getType();
Gson gson = new Gson();
String jsonPerson = gson.toJson(person, personType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With