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 ?
Overview. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want.
The JSON Parsing API is intended to provide fast parsing of a JSON data stream with very little memory required. It is an event-driven API that uses callbacks (handlers) to report when things are found in the JSON document. The parser does not build a document structure for you.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With