I am new to gson and ask a new question that I could not find an answer to, so please bear with me. StackOverflow and google were not my friend :(
I have a "User" java class, and one of its "externalProfile" properties is a Java string containing already serialized JSON. When gson serializes the User object, it will treat the externalProfile file as primitive and thus avoiding adding JSON slashes, etc. I want gson to leave the string alone, just using it βas isβ, because it is already valid and JSON is applicable.
To distinguish the JSON string, I created a simple JSONString class, and I tried using reader / writers, registerTypeAdapter, but nothing works. Can you help me?
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);
}
, ( String):
{"profile":{"registrationNumber": 11111}}
, JSONString User, JSON:
User user = new User();
user.setExternalProfile(new JSONString(externalProfile)),
String json = customJsonBuilder(user);
json - :
{\"profile\":{\"registrationNumber\": 11111}}
, JSONString gson String, .
, gson JSONString , JSON.
/-, .