java 解析json, 带转义字符的json

来源:互联网 发布:美图软件大全 编辑:程序博客网 时间:2024/06/06 01:11

一:解析普通json

      1:不带转化字符

       格式{"type":"ONLINE_SHIPS","message":{"currentTime":1400077615368,"direction":0,"id":1,"latitude":29.5506,"longitude":106.6466}}      

JSONObject jsonObject = new JSONObject(jsonstr).getJSONObject("message");System.out.println("currentTime:"+jsonObject.get("currentTime"));System.out.println("direction:"+jsonObject.get("direction"));System.out.println("latitude:"+jsonObject.get("latitude"));System.out.println("longitude:"+jsonObject.get("longitude"));


      jsonarray    

JSONObject jo = ja.getJSONArray("cargoList").getJSONObject(0);



    2:带转义字符的json格式

    {"type":"ONLINE_SHIPS","message":"{\"currentTime\":1400077615368,\"direction\":0,\"id\":1,\"latitude\":29.5506,\"longitude\":106.6466}"}

     其实也很简单,先把它转化成字符串就可以了

JSONObject jsonObject = new JSONObject(jsonstr);//先通过字符串的方式得到,转义字符自然会被转化掉String jsonstrtemp = jsonObject.getString("message");System.out.println("message:"+jsonstrtemp);jsonObject = new JSONObject(jsonstrtemp);System.out.println("currentTime:"+jsonObject.get("currentTime"));System.out.println("direction:"+jsonObject.get("direction"));System.out.println("latitude:"+jsonObject.get("latitude"));System.out.println("longitude:"+jsonObject.get("longitude"));



二:遍历Json对象

     

JSONObject ports = ja.getJSONObject("ports");Iterator<String> keys = ports.keys();while(keys.hasNext()){             String key=keys.next();             String value = ports.getString(key);        }
0 0
原创粉丝点击