简体   繁体   中英

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

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

Json example:

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

The dynamic-fields will change its name depending on the structure sent.

Is there a way ?

You can use custom (de)serialization as Raph Levien suggests, however, Gson natively understands maps.

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

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

The map can now contain your dynamic keys. To read that Json again you need to tell Gson about the type information through a TypeToken which is Gson's way of recording the runtime type information that Java erases.

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

I hope that helps. :)

Using google-gson I do it this way:

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

and then you can work with json. eg:

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

Yes, write a custom deserializer that takes a generic JsonElement object. Here's an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM