Prevent GSON from serializing JSON string

5,146 views
Skip to first unread message

TheXL

unread,
Jun 13, 2015, 12:04:56 PM6/13/15
to googl...@googlegroups.com
I'm new to gson, and have newby question which I have not found an answer to, so please bear with me. StackOverflow and google were not my friend :(

I have a java class "User", and one of its properties, "externalProfile" is a Java String containing already serialized JSON. When gson serializes the User object, it will treat externalProfile as primitive and thus escaping the JSON adding extra slashes etc. I want gson to leave the string alone, just using it "as is", because it is already valid and usable JSON.

To distinguish the JSON string, I created a simple class called JSONString, and I've tried using reader/writers, registerTypeAdapter, but nothing works. Can you help me out?

public class User {
   
private JSONString 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);
}



BTW: I post this for the second time, because the first time it didn;t work for some reason. Hop this doesn't double my entry.

TheXL

unread,
Jun 14, 2015, 10:25:31 AM6/14/15
to googl...@googlegroups.com
As en example, the externalProfile will hold (as String value):

  
  {"profile":{"registrationNumber": 11111}}



After I store it as JSONString in the User object, and we convert the user object to JSON:

   
User user = new User();
    user
.setExternalProfile(new JSONString(externalProfile)),  
   
String json = customJsonBuilder(user);



json will hold something like:

    {\"profile\":{\"registrationNumber\": 11111}}



So, the externalProfile JSONString is serialized by gson as String primitive, adding the extra slashes in front of the doublequotes.
I want gson to leave this JSONString as is, because it already is usable JSON.
I'm looking for a type adapter / reader-writer to do this, but I can't get it to work.

TheXL

unread,
Jun 15, 2015, 3:09:00 AM6/15/15
to googl...@googlegroups.com
As suggested by AlexisC at  Stack Overflow, the simples way is to first convert the JSON String to gson's native JsonObject, and then serialize it again:
new Gson().fromJson(externalProfile, JsonObject.class)

So simple, I don;t understand how I've missed it


Reply all
Reply to author
Forward
0 new messages