termigrator
termigrator

Reputation: 159

Java parse JSON String to array or objectlist

I'm not very familiar with Java, but got the job to reverse the following JSON-Output to a JAVA object-structure:

Sample:

{"MS":["FRA",56.12,11.67,"BUY"],"DELL":["MUC",54.76,9.07,"SELL"]}

Does someone know, how to build the Arrays / Objetcs and the code to read the strings with Java? JSON or GSON codesamples are welcome.

Thanks!

Upvotes: 1

Views: 2438

Answers (2)

travega
travega

Reputation: 8415

You could try something like:

Gson gson = new Gson();

Type type = new TypeToken<HashMap<String, String>>(){}.getType();

HashMap<String, String> map = new HashMap<String, String>();
map = gson.fromJson( json, type );

Where "json" is the json string you defined.

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340723

Jackson library is most commonly used to parse JSON in Java. Forget about regular expressions and parsing by hand, this is more complicated than you might think. It all boils down to:

String json = "{\"MS\":[\"FRA\",56.12,11.67,\"BUY\"],\"DELL\":[\"MUC\",54.76,9.07,\"SELL\"]}";

ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(json, Map.class);

You can also map directly to Java beans.

Upvotes: 1

Related Questions