Karl Green Karl Green - 2 months ago 25
Android Question

Why does Gson toJson always return null?

When I try to convert a basic object to json, it seems to return null with everything I have 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);

Answer

This problem has nothing to do with Gson.

You are not instantiating the object correctly. Java doesn't support named arguments in the same way that a language like Python or Objective C does. Your code doesn't compile when I try to make it a complete program, like below:

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

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

        System.out.println(person.Name);
    }
}

See here: http://ideone.com/maqTGw

compilation info
Main.java:18: error: <identifier> expected
      Name = "John";
          ^
Main.java:19: error: <identifier> expected
      Address = "London";
             ^
Main.java:20: error: ';' expected
    }

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