java - Gson.toJson(Object) returning object hash code -
i'm trying transform class below using gson.tojson(object)
method, returing me object hash code of class, eg: br.com.helpradar.entity.user@475fdaaa
however, can retrieve user.expertise without problems , relationships: gson.tojson(user.getexpertise)
@entity @sequencegenerator(name="sequser", sequencename="seq_user", allocationsize=1) public class user { @id private long id; @column(nullable=false) private string name; @onetoone private contact contact; //enum private typeuser typeuser; @manytomany(cascade = { cascadetype.all }) @jointable(name = "user_review", joincolumns = { @joincolumn(name = "user_id") }, inversejoincolumns = { @joincolumn(name = "review_id") }) @column(name="review") private set<review> review= new hashset<review>(); @manytomany(cascade = { cascadetype.all }) @jointable(name = "user_expertise", joincolumns = { @joincolumn(name = "user_id") }, inversejoincolumns = { @joincolumn(name = "expertise_id") }) @column(name="expertise") private set<expertise> expertise = new hashset<expertise>(); }
this gson method:
gson gson = new gsonbuilder() .registertypeadapter(user.class, new mytypeadapter<expertise>()) .registertypeadapter(user.class, new mytypeadapter<review>()) .create(); homecoming gson.tojson(user);
this mytypeadapter:
class mytypeadapter<t> extends typeadapter<t> { public t read(jsonreader reader) throws ioexception { homecoming null; } public void write(jsonwriter writer, t obj) throws ioexception { if (obj == null) { writer.nullvalue(); return; } writer.value(obj.tostring()); }
}
so, how gson.tojson(user)
homecoming json string can utilize gson.fromjson on other end? in advance.
i think need utilize method enablecomplexmapkeyserialization(). here can see next documentation:
public gsonbuilder enablecomplexmapkeyserialization() enabling feature alter serialized form if map key complex type (i.e. non-primitive) in serialized json form. default implementation of map serialization uses tostring() on key...
and example:
gson gson = new gsonbuilder() .register(point.class, new mypointtypeadapter()) .enablecomplexmapkeyserialization() .create(); map<point, string> original = new linkedhashmap<point, string>(); original.put(new point(5, 6), "a"); original.put(new point(8, 8), "b"); system.out.println(gson.tojson(original, type));
output be:
{ "(5,6)": "a", "(8,8)": "b" }
so, can seek this:
gson gson = new gsonbuilder() .registertypeadapter(user.class, new mytypeadapter<expertise>()) .registertypeadapter(user.class, new mytypeadapter<review>()) .enablecomplexmapkeyserialization() .create();
java json gson
No comments:
Post a Comment