How to decode a json string with gson in java?

自闭症网瘾萝莉.ら 提交于 2019-12-10 21:57:24

问题


I have a json string (the stream of social network Qaiku). How can I decode it in Java? I've searched but any results work for me. Thank you.


回答1:


As an example using Gson, you could do the following

Gson gson = new Gson();
gson.fromJson(value, type);

where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.

The following example shows decoding a JSON string into a list of domain objects called Table:

http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/

In order to do that the type needs to be specified as:

Type type = new TypeToken<List<Table>>(){}.getType();

Gson is available here:

http://code.google.com/p/google-gson/




回答2:


Standard way of object de-serialization is the following:

Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);

For primitives corresponding class should be used instead of MyType.

You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.



来源:https://stackoverflow.com/questions/6081595/how-to-decode-a-json-string-with-gson-in-java

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