Reputation: 167
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 ?
Upvotes: 5
Views: 7665
Reputation: 3714
Using google-gson I do it this way:
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g.:
String value = root.getAsJsonObject().get("type").getAsString();
Upvotes: 3
Reputation: 4748
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. :)
Upvotes: 8
Reputation: 5218
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/
Upvotes: 1