Json-path学习笔记<二>
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, \, /, \r, \n, \b, \f, \t 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 incorrectSystem.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文档