Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 967
Bruno Carvalho Avatar asked Jan 27 '11 15:01

Bruno Carvalho


People also ask

What is Gson used for?

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.

What is JSONPath parse?

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.

What is API parsing?

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.


1 Answers

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. :)

like image 107
alpian Avatar answered Oct 18 '22 21:10

alpian