我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
当前回答
对于仍在寻找答案的人:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
其他回答
注意,反序列化接口的GSON将导致如下异常。
"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
而反序列化;GSON不知道该接口需要调用哪个对象。
这个问题在这里得到了解决。
然而FlexJSON本身就有这个解决方案。而序列化时间,它是添加类名作为json的一部分,如下所示。
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
JSON会有些麻烦;但是你不需要编写GSON中需要的InstanceCreator。
将字符串转换为json, sting就像json一样。{“phonetype”:“N95”,“猫”:“WP”}
String Data=response.getEntity().getText().toString(); // reading the string value
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
我喜欢为此使用google-gson,这正是因为我不需要直接使用JSONObject。
在这种情况下,我将有一个类,将对应于JSON对象的属性
class Phone {
public String phonetype;
public String cat;
}
...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...
然而,我认为你的问题更像是,我如何从JSON字符串中得到一个实际的JSONObject对象。
我在看google-json api,找不到任何直接的东西 org。json的api,这可能是你想要使用的,如果你非常需要使用一个基本的JSONObject。
http://www.json.org/javadoc/org/json/JSONObject.html
使用org.json.JSONObject(另一个完全不同的API)如果你想做一些像…
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));
我认为google-gson的美妙之处在于您不需要处理JSONObject。你只需要获取json,传递想要反序列化的类,你的类属性就会与json匹配,但话说回来,每个人都有自己的需求,也许你不能奢侈地在反序列化端拥有预先映射的类,因为json生成端可能太动态了。在这种情况下,只需使用json.org。
用于设置json单一对象为列表 即
"locations":{
}
in to List<Location>
use
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
jackson.mapper-asl-1.9.7.jar
对于仍在寻找答案的人:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);