Java parse JSON String to array or objectlist

一曲冷凌霜 提交于 2019-12-11 11:00:52

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9708918/java-parse-json-string-to-array-or-objectlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!