I am using the Gson parser in Java 7. I would like to preserve one of my properties as a raw JSON string so I can deserialize it into the desired class later.
Example input JSON:
{
"foo":"bar",
"body":["blah"]
}
or
{
"foo":"bar",
"body":{"a":"b"}
}
Deserializes to a class like this:
public class Message {
public String foo;
public String bar; //I want this to be a raw JSON string, not parsed
}
Code:
String input = "{\"foo\":\"bar\", \"body\":[\"blah\"]}";
Message message = gson.fromJson(input, Message.class);
message.foo; //"bar"
message.body; //"[\"blah\"]"
Is this possible?
UPDATE:
I'm currently doing this, but it would be nice if it could be "cleaner" and use the native String
type somehow...
public class Message {
public String foo;
public JsonString body;
}
public static class JsonString {
public String body;
}
public static class JsonStringDeserializer implements JsonDeserializer<JsonString> {
@Override
public JsonString deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonString a = new JsonString();
a.body = json.toString();
return a;
}
}
The thing I don't like about this is that I have to use the deserialized object like so:
Message message = gson.fromJson(input, Message.class);
//notice how i have to use the inner string
SomeClass cls = gson.fromJson(message.body.body, SomeClass.class);