Java解析Json小例子


Java解析Json小例子,包含了遍历未知Key的json键值对。操作json数组。使用的是阿里的fastjson工具包。

json在线解析工具: http://www.jsonin.com/



package com.jd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Iterator;

/**
 * Created by cc on 2016/3/8.
 */
public class JsonMainClass {

    public static void main(String args[]){

        /*
            {
              "cluster_name": "21test",
              "hearth": "true",
              "nodes": {
                "abc": {
                  "ip": "192.168.200.191",
                  "version": "2.1.1"
                },
                "def": {
                  "ip": "192.168.200.191",
                  "version": "2.1.1"
                },
                "ghi": {
                  "ip": "192.168.200.196",
                  "version": "2.1.1"
                }
              }
            }
         */

        String jsonStr = "{\"cluster_name\":\"21test\",\"hearth\":\"true\",\"nodes\":{\"abc\":{\"ip\":\"192.168.200.191\",\"version\":\"2.1.1\"},\"def\":{\"ip\":\"192.168.200.191\",\"version\":\"2.1.1\"},\"ghi\":{\"ip\":\"192.168.200.196\",\"version\":\"2.1.1\"}}}";

        JSONObject jo = JSONObject.parseObject(jsonStr);
        System.out.println(jo.getString("cluster_name"));//21test
        System.out.println(jo.getJSONObject("nodes").size());//3
        System.out.println(jo.getJSONObject("nodes").getJSONObject("def"));//{"ip":"192.168.200.191","version":"2.1.1"}

        JSONObject nodes = jo.getJSONObject("nodes");
        Iterator it = nodes.keySet().iterator();//遍历未知key的json
        while (it.hasNext()) {
            String key = it.next().toString();
            System.out.println(key + " " + nodes.getJSONObject(key).getString("ip") + " " + nodes.getJSONObject(key).getString("version"));
        }

        //测试getJSONArray()
        String arrayJson = "{\"info\":[{\"goodsId\":\"1234\",\"goodsq\":\"10\"},{\"goodsId\":\"5678\",\"goodsq\":\"20\"}]}";
        testArray(arrayJson);
    }

    /*
        {
          "info": [
            {
              "goodsId": "1234",
              "goodsq": "10"
            },
            {
              "goodsId": "5678",
              "goodsq": "20"
            }
          ]
        }
    */
    //json数组
    public static void testArray(String jsonStr){
        JSONObject jo = JSONObject.parseObject(jsonStr);
        JSONArray arrayJson = jo.getJSONArray("info");
        for (int i = 0; i < arrayJson.size(); i++) {
            JSONObject arrayNode = arrayJson.getJSONObject(i);
            System.out.println(arrayNode.getString("goodsId"));
            /* 输出
                     1234
                     5678
            */
        }
    }


}


你可能感兴趣的:(Java)