java - Prevent GSON from serializing JSON string -
i'm new gson, , have newby question have not found answer to, please bear me. stackoverflow , google not friend :(
i have java class "user", , 1 of properties, "externalprofile" java string containing serialized json. when gson serializes user object, treat externalprofile primitive , escaping json adding slashes etc. want gson leave string alone, using "as is", because valid , usable json.
to distinguish json string, created simple class called jsonstring, , i've tried using reader/writers, registertypeadapter, nothing works. can me out?
public class user { private jsonstring externalprofile; public void setexternalprofile(jsonstring externalprofile) { this.externalprofile = externalprofile; } } public final class jsonstring { private string simplestring; public jsonstring(string simplestring) { this.simplestring = simplestring; } } public customjsonbuilder(object object) { gsonbuilder builder = new gsonbuilder(); builder.registertypeadapter(gregoriancalendar.class, new jsonserializer<gregoriancalendar>() { public jsonelement serialize(gregoriancalendar src, type type, jsonserializationcontext context) { if (src == null) { return null; } return new jsonprimitive(new simpledateformat("yyyy-mm-dd hh:mm:ss").format(src.gettime())); } }); gson gson = builder.create(); return gson.tojson(object); }
as en example, externalprofile hold (as string value):
{"profile":{"registrationnumber": 11111}}
after store jsonstring in user object, , convert user object json:
user user = new user(); user.setexternalprofile(new jsonstring(externalprofile)), string json = customjsonbuilder(user);
json hold like:
{\"profile\":{\"registrationnumber\": 11111}}
so, externalprofile jsonstring serialized gson string primitive, adding slashes in front of doublequotes. want gson leave jsonstring is, because usable json. i'm looking type adapter / reader-writer this, can't work.
as stated alexis c:
store externalprofile jsonobject first:
new gson().fromjson(externalprofile, jsonobject.class));
and let gson serialize again when outputting user object. produce same json!
Comments
Post a Comment