最近遇到一个java解析json的问题,困扰了好久,网上搜到的好多都是解析数组格式的,不过想了好久其实问题挺简单的......
json:
{"my_type":"status","update_time":12312352522,"my_value":{"in":[{"ele_name":"IN1","ele_status":1,"ele_enable":0},{"ele_name":"IN2","ele_status":1,"ele_enable":0},{"ele_name":"IN3","ele_status":1,"ele_enable":0},{"ele_name":"IN4","ele_status":1,"ele_enable":0},{"ele_name":"IN5","ele_status":1,"ele_enable":0},{"ele_name":"IN6","ele_status":1,"ele_enable":0}],"out":[{"ele_name":"Out1"},{"ele_name":"Out2"},{"ele_name":"Out3"},{"ele_name":"Out4"}]}}
可以先用json格式化工具看一下绝对没问题的
用到的jar包:json-lib-2.3-jdk15.jar
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
新建一个Test类
public class Test {
public static void main(String[] args) {
test3();
}
private static void test3(){
//windows下“\”作为转义字符,可以帮助输出双引号
String json="{\"my_type\":\"status\",\"update_time\":12312352522,\"my_value\":{\"in\":[{\"ele_name\":\"IN1\",\"ele_status\":1,\"ele_enable\":0},{\"ele_name\":\"IN2\",\"ele_status\":1,\"ele_enable\":0},{\"ele_name\":\"IN3\",\"ele_status\":1,\"ele_enable\":0},{\"ele_name\":\"IN4\",\"ele_status\":1,\"ele_enable\":0},{\"ele_name\":\"IN5\",\"ele_status\":1,\"ele_enable\":0},{\"ele_name\":\"IN6\",\"ele_status\":1,\"ele_enable\":0}],\"out\":[{\"ele_name\":\"Out1\"},{\"ele_name\":\"Out2\"},{\"ele_name\":\"Out3\"},{\"ele_name\":\"Out4\"}]}}";
try {
JSONObject jsonObject = JSONObject.fromObject(json);
String my_value = jsonObject.getString("my_value");
String my_type = jsonObject.getString("my_type");
System.out.println("my_type is:" + my_type);
//将得到的字符串在进行格式化
JSONObject jsonObject1 = JSONObject.fromObject(my_value);
String in = jsonObject1.getString("in");
System.out.println("in is:" + in);
String out = jsonObject1.getString("out");
System.out.println("out is:" + out);
JSONArray jsonArray = JSONArray.fromObject(in);
Object[] os = jsonArray.toArray();
for(Object o:os){
System.out.println(o);
}
JSONArray jsonArray1 = JSONArray.fromObject(out);
Object[] os1 = jsonArray1.toArray();
for(Object o:os1){
System.out.println(o);
}
} catch (JSONException e) {
e.printStackTrace();
}
}