我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
当前回答
使用org.json
如果你有一个包含JSON格式文本的字符串,那么你可以通过以下步骤获取JSON对象:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
现在访问phonetype
Sysout.out.println(jsonObject.getString("phonetype"));
其他回答
注意,反序列化接口的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主页可以链接到各种Java JSON序列化器和反序列化器。
在撰写本文时,有22种:
JSON-java. JSONUtil. JSONP. 杰森-利布。 字符串树。 索乔。 json-taglib. Flexjson。 阿尔戈。 杰索尼。 法斯特森。 姆森。 杰森。 JSON-简单。 json-io. 谷歌-格森。 福斯新星JSON。 玉米转换器。 阿帕奇·约翰松。 根森。 库克森。 程序库。
...当然,这个名单是可以改变的。
那些因为弃用问题而无法从发布的答案中找到解决方案的人,可以使用com.google.gson中的JsonParser。
例子:
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));
Codehaus Jackson -自2012年以来,我一直是这个很棒的API,用于我的RESTful webservice和JUnit测试。使用它们的API,你可以:
(1)转换JSON字符串到Java bean
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2)将JSON字符串转换为JSON对象(JsonNode)
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3)转换Java bean到JSON字符串
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
参考文献:
Codehaus杰克逊 JsonNode API——如何使用、导航、解析和计算来自JsonNode对象的值 教程-简单的教程,如何使用Jackson将JSON字符串转换为JsonNode
用于设置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