Decontaminate an object containing JSON using GSON

I am using gson to deserialize POJOs from JSON views.

I would like one of the fields in one of my POJOs to contain arbitrary JSON data. For instance:

class B { public String stringField; public JsonObject jsonField; } 

I would like to call Gson.fromJson(json, B.class) on the following JSON:

 { "stringField": "booger", "jsonField" : { "arbitraryField1": "foo" } } 

and get a B.jsonField containing a JsonObject with arbitraryField foo values.

However, when I try to do this, jsonField always an empty object ( {} ). In fact, more generally, it seems that the following always returns an empty object:

 new Gson().fromJson("{ foo: 1 }", JsonObject.class) 

I would expect the above to return an object containing a field named foo value 1.

How can I save gson arbitrary json data while json deserialization for POJOS?

+4
source share
3 answers

I managed to get around this problem by introducing a wrapper object containing JsonObject, and then wrote a custom deserializer for this object, which simply returns the original json. However, there seems to be a better way.

For posterity, the deserializer and trivial wrapper object look like this:

 class MyJsonObjectWrapperDeserializer implements JsonDeserializer<MyJsonObjectWrapper> { @Override public MyJsonObjectWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new MyJsonObjectWrapper(json.getAsJsonObject()); } } class MyJsonObjectWrapper { public JsonObject json; public MyJsonObjectWrapper(JsonObject json) { this.json = json; } } 
+3
source

you can use JsonParser:

 JsonParser parser = new JsonParser(); JsonObject o = parser.parse("{ \"foo\": \"1\" }").getAsJsonObject(); 
+2
source

Consider this deserializer, which is my interpretation of the document .

 import com.google.gson.*; import java.lang.reflect.Type; class B { public String stringField; public JsonObject jsonField; } class BDeserializer implements JsonDeserializer<B> { public B deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); B b = new B(); b.stringField = jsonObject.get("stringField").getAsString(); b.jsonField = jsonObject.getAsJsonObject("jsonField"); return b; } } public class Test { static public void main(String[] args) { GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(B.class, new BDeserializer()); String json = " { \"stringField\" : \"booger\", \"jsonField\" : { \"arbitraryField1\" : \"foo\" } } "; B b = gson.create().fromJson(json, B.class); System.out.println(b.stringField); System.out.println(b.jsonField.toString()); } } 
+1
source

Source: https://habr.com/ru/post/1433698/


All Articles