我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
我有一个名为jsonString的字符串变量:
{"phonetype":"N95","cat":"WP"}
现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!
当前回答
将字符串转换为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);
其他回答
最好使用更简单的方式使用org。json自由。只需要做一个非常简单的方法:
JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");
现在obj是你各自String的JSONObject转换形式。这是在有名称-值对的情况下。
对于字符串,可以直接传递给JSONObject的构造函数。如果它是一个有效的json String,那么好,否则它会抛出异常。
对于仍在寻找答案的人:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
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
如果您正在使用http://json-lib.sourceforge.net (net.sf.json.JSONObject)
这很简单:
String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);
or
JSONObject json = JSONSerializer.toJSON(myJsonString);
获取值,然后用 json.getString(param), json.getInt(param)等等。