I would like to serialize this object to JSON String
public class Person {
public String id;
public String name;
public Person parent;
}
and obtain a result like this:
{id: 1, name: "Joe", parent: 2}
I tried to use
Person p = new Person(1, "Joe", new Person(2, "Mike"));
Gson gson = new GsonBuilder()
.registerTypeAdapter(Persona.class, new PersonSerializer()).create();
String str = gson.toJson(p);
but instead of that, I got:
"1"
PersonSerializer:
public class PersonSerializer implements JsonSerializer<Person> {
public JsonElement serialize(Person src, Type typeOfSrc, ...) {
return new JsonPrimitive(src.id);
}
}
Please any suggestion is welcome
Thanks,
Mario
Best Solution
In order to get the result you desire, you need to write the serializer like this:
The result for
will be
Complete code: