How to use Google Json Parsing API (Gson) to parse some dynamic fields in json?

I have structured Json that can be modified in some fields, how can I parse (deserialize) it correctly in Java using the Gson google json api?

Json example:

{ 
type: 'sometype',
fields: {
    'dynamic-field-1':[{value: '', type: ''},...],
    'dynamic-field-2':[{value: '', type: ''},...],
...
}

Dynamic fields will change their name depending on the structure sent.

Is there any way?

+5
source share
3 answers

You can use regular serialization (de), as Raf Levien says, however Gson initially understands maps.

If you run this, you will get the result {"A": "B"}

Map<String, String> map = new HashMap<String, String>();
map.put("A", "B");
System.out.println(new Gson().toJson(src));

. Json, Gson TypeToken, Gson , Java.

Map fromJson = 
    new Gson().fromJson(
        "{\"A\":\"B\"}", 
        new TypeToken<HashMap<String, String>>() {}.getType());
System.out.println(fromJson.get("A"));

, .:)

+8

google-gson :

JsonElement root = new JsonParser().parse(jsonString);

json. :.

String value = root.getAsJsonObject().get("type").getAsString();
+3

Yes, write your own deserializer that accepts a shared JsonElement object. Here is an example:

http://benjii.me/2010/04/deserializing-json-in-android-using-gson/

+1
source

All Articles