Json-path學習筆記

oven發表於2015-09-23

Json-smart

該篇主要以程式碼示例為主,因為google上不去,看不到Json-smart這個官方文件和API。故只例舉一些程式碼示例。因為接下來的Json-path底層預設使用的就是JsonSmart。JsonSmart的原始碼並不多,有興趣可以去看看

解析簡單json格式的字串

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

public class ParseJsonString {

    public static void main(String[] args) {
        /**
         * <pre>
         * [
         *       0,
         *       {
         *           `1`: {
         *               `2`: {
         *                   `3`: {
         *                       `4`: [
         *                           5,
         *                           {
         *                               `6`: 7
         *                           }
         *                       ]
         *                   }
         *               }
         *           }
         *       }
         *   ]
         * </pre>
         * */
        String str="[0,{`1`:{`2`:{`3`:{`4`:[5,{`6`:7}]}}}}]";
        if (JSONValue.isValidJson(str)) { //判斷是否是合法的json字串
            Object obj=JSONValue.parse(str);
            JSONArray array=(JSONArray)obj;
            System.out.println(array.size());
            System.out.println(array);
            JSONObject jsonObject = (JSONObject) array.get(1);
            System.out.println(jsonObject);
            JSONObject jsonObject1 = (JSONObject) jsonObject.get("1");
            System.out.println(jsonObject1.toJSONString());
            JSONObject jsonObject2 = (JSONObject) jsonObject1.get("2");
            System.out.println(jsonObject2.toJSONString());
            JSONObject jsonObject3 = (JSONObject) jsonObject2.get("3");
            System.out.println(jsonObject3.toJSONString());
            JSONArray array2 =  (JSONArray) jsonObject3.get("4");
            System.out.println(array2);
            JSONObject jsonObject4 = (JSONObject) array2.get(1);
            System.out.println(jsonObject4.toJSONString());
            int data = Integer.parseInt(jsonObject4.get("6").toString());
            System.out.println(data);
        }
    }
}

輸出:

2
[0,{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}]
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
{"2":{"3":{"4":[5,{"6":7}]}}}
{"3":{"4":[5,{"6":7}]}}
{"4":[5,{"6":7}]}
[5,{"6":7}]
{"6":7}
7

JSONValue的使用

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONStyle;
import net.minidev.json.JSONValue;
import net.minidev.json.parser.ParseException;

public class JsonValueTest {
    public static void main(String[] args) throws ParseException, IOException {
        // public class JSONObject extends HashMap<String, Object> 
        //              implements JSONAware, JSONAwareEx, JSONStreamAwareEx {}
        JSONObject obj = new JSONObject();
        obj.put("name", "foo");
        obj.put("num", 100);
        obj.put("balance", 1000.21);
        obj.put("is_vip", true);
        obj.put("is_special_fuhao", "`");
        obj.put("nickname", null);
        // 判斷是否是合法的json串
        System.out.println(JSONValue.isValidJson(obj.toJSONString()));
        // 轉義 quotes, , /, 
, 
, , f, 	 and other control characters (U+0000 through U+001F).
        System.out.println(JSONValue.escape(obj.toJSONString()));
        System.out.println(obj.toJSONString());
        System.out.println(JSONValue.toJSONString(obj));
        // JSONStyle object configure JSonSerializer reducing output size
        System.out.println(obj.toJSONString(JSONStyle.NO_COMPRESS));
        System.out.println(obj.toJSONString(JSONStyle.MAX_COMPRESS));
        System.out.println(JSONValue.toJSONString(obj, JSONStyle.MAX_COMPRESS));
        System.out.println(JSONValue.compress(obj.toJSONString()));
        System.out.println(JSONValue.uncompress(obj.toJSONString()));
        System.out.println(JSONValue.uncompress(JSONValue.toJSONString(obj, JSONStyle.MAX_COMPRESS)));
        // Parse Json input to a java Object keeping element order
        System.out.println(JSONValue.parseKeepingOrder(obj.toJSONString()));
        // 解析字串的時候會拋異常 throw ParseException
        System.out.println(JSONValue.parseWithException(obj.toJSONString()));
        System.out.println("**********************************");
        String str="{"key":"Value"}";
        Object obj1=JSONValue.parse(str);
        System.out.println(obj1); 
        obj1=JSONValue.parseStrict(str);
        System.out.println(obj1); 
        JSONObject obj2=(JSONObject)obj1;
        System.out.println(obj2.get("key"));
        System.out.println("**********************************");
        StringBuffer strBuffer = new StringBuffer("zhangsan");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hello", "world");
        map.put("hello1", "world1");
        map.put("hello2", "world2");
        JSONValue.writeJSONString(map, strBuffer, JSONStyle.NO_COMPRESS);
//        JSONValue.writeJSONString(map, strBuffer, JSONStyle.MAX_COMPRESS);
//        如果設定JSONStyle.MAX_COMPRESS,那麼strBuffer輸出: zhangsan{hello:world,hello2:world2,hello1:world1}
        System.out.println(strBuffer);
    }
}

輸出:

true
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{balance:1000.21,num:100,is_vip:true,name:foo,is_special_fuhao:"`"}
{balance:1000.21,num:100,is_vip:true,name:foo,is_special_fuhao:"`"}
{balance:1000.21,num:100,nickname:null,is_vip:true,name:foo,is_special_fuhao:"`"}
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{"balance":1000.21,"num":100,"is_vip":true,"name":"foo","is_special_fuhao":"`"}
{balance=1000.21, num=100, nickname=null, is_vip=true, name=foo, is_special_fuhao=`}
{"balance":1000.21,"num":100,"is_vip":true,"nickname":null,"name":"foo","is_special_fuhao":"`"}
**********************************
{"key":"Value"}
{"key":"Value"}
Value
**********************************
zhangsan{"hello":"world","hello2":"world2","hello1":"world1"}

JSONValue中所有的parse方法內部都是呼叫JSONParser實現的parse的方法。

  • JSONValue.parse() 和 JSONValue.parseStrict() 功能是一致的。區別是JSONValue.parse()不會丟擲異常,而JSONValue.parseStrict()會丟擲ParseException異常。

  • JSONValue.parseStrict()和JSONValue.parseWithException() 都會丟擲ParseException異常,單從輸出結果看二者是一樣的,區別是JSONValue.parseStrict()的解析輸入的json文字的有效性是依據RFC4627。而JSONValue.parseWithException()解析輸入的json文字內容依據預設的解析文字的模式。

JsonValue的remapField方法以及對於編碼轉換

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import net.minidev.json.writer.JsonReader;


public class JsonReaderTest {

    static String[] nonLatinTexts = new String[] { "සිංහල ජාතිය", "日本語", "Русский", "فارسی", "한국어", "Հայերեն", "हिन्दी", "עברית", "中文", "አማርኛ", "മലയാളം", "ܐܬܘܪܝܐ", "მარგალური" };
    public static void main(String[] args) throws IOException {
        String text = "{`new`:`foo`,`default`:`bar`}";
        JSONValue.remapField(TRen.class, "default", "default_");
        JSONValue.remapField(TRen.class, "new", "new_");
        TRen t = JSONValue.parse(text, TRen.class);
        System.out.println(JSONValue.toJSONString(t));
        System.out.println("*******************************");
        for (String nonLatinText : nonLatinTexts) {
            String s = "{"key":"" + nonLatinText + ""}";
//            1. StringReader reader = new StringReader(s);
//               JSONObject obj = (JSONObject) JSONValue.parse(reader);
//            2. ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes("utf8"));
//               JSONObject obj = (JSONObject) JSONValue.parse(bis);
//            3. byte[] bs = s.getBytes("utf8");
//               JSONObject obj = (JSONObject) JSONValue.parse(bs);
            JSONObject obj = (JSONObject) JSONValue.parse(s);
            String v = (String) obj.get("key"); // result is incorrect
            System.out.print(v + ", ");
        }
        System.out.println();
    }
    public static class TRen {
        public String new_;
        public String default_;
    }
}

輸出

{"default":"bar","new":"foo"}
*******************************
සිංහල ජාතිය, 日本語, Русский, فارسی, 한국어, Հայերեն, हिन्दी, עברית, 中文, አማርኛ, മലയാളം, ܐܬܘܪܝܐ, მარგალური, 

Json轉Object示例

import java.util.ArrayList;
import java.util.List;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

public class JsonToObject {
    public static void main(String[] args) {
        People people = new People();
        people.setName("test1");
        people.setAge(13);
        people.setMobile(20130808);

        People people1 = new People();
        people1.setName("test");
        people1.setAge(123);
        people1.setMobile(888666);

        List<People> array = new ArrayList<People>();
        array.add(people);
        array.add(people1);
        JSONObject obj = new JSONObject();
        obj.put("peoples", array);
        System.out.println(JSONValue.toJSONString(obj));
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(people);
        jsonArray.add(people1);
        JSONObject result = new JSONObject();
        result.put("peoples", jsonArray);
        System.out.println(JSONValue.toJSONString(result));
    }
}

class People {
    public String name;
    public int age;
    public boolean single;
    public long mobile;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isSingle() {
        return single;
    }
    public void setSingle(boolean single) {
        this.single = single;
    }
    public long getMobile() {
        return mobile;
    }
    public void setMobile(long mobile) {
        this.mobile = mobile;
    }
}

輸出:

{"peoples":[{"single":false,"age":13,"name":"test1","mobile":20130808},{"single":false,"age":123,"name":"test","mobile":888666}]}
{"peoples":[{"single":false,"age":13,"name":"test1","mobile":20130808},{"single":false,"age":123,"name":"test","mobile":888666}]}

參考文件:
Json-smart在gitHub上的程式碼
JsonSmart文件