资讯专栏INFORMATION COLUMN

Json-path学习笔记<二>

Soarkey / 779人阅读

摘要:该篇主要以代码示例为主,因为上不去,看不到这个官方文档和。因为接下来的底层默认使用的就是。和功能是一致的。区别是不会抛出异常,而会抛出异常。而解析输入的文本内容依据默认的解析文本的模式。

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) {
        /**
         * 
         * [
         *       0,
         *       {
         *           "1": {
         *               "2": {
         *                   "3": {
         *                       "4": [
         *                           5,
         *                           {
         *                               "6": 7
         *                           }
         *                       ]
         *                   }
         *               }
         *           }
         *       }
         *   ]
         * 
* */ 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 
        //              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 map = new HashMap();
        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 array = new ArrayList();
        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文档

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64570.html

相关文章

  • Json-path学习笔记&lt;一&gt;

    摘要:简介是用于结构化数据序列化的一种文本格式,包含种基础类型字符串,数字,布尔和和两种结构类型对象和数组。对象是一个由零或者多个名值对组成的无序集合,其中名值对中名是字符串类型,值则可以是字符串,数字,布尔,,对象或数组类型。 Json JavaScript Object Notation (JSON)是一个轻量级的,基于文本的,跨语言的数据交换格式。它从ECMAScript编程语言标准(...

    Vicky 评论0 收藏0
  • pygame学习笔记之设置字体及显示中文

      pygame作为python的一个平台库,在做游戏的时候,需要学习的内容还是比较的多的,主要涉及到的内容有相关的学习笔记,包括怎么设置字体,另外还有就是怎么设置其显示中文呢?下面就给大家详细解答下。  一、获得可用字体  importpygame   print(pygame.font.get_fonts())  结果:  ['arial','arialblack...

    89542767 评论0 收藏0
  • pygame学习笔记之设置字体及显示中文

      游戏界面,国外的一些游戏,还是以英文为主,那么,国内的游戏,大多覆盖的是中文字体。那么,我们怎么样将英文字体修改成为中文,并且能够正确的显示出来呢?下面就给大家详细解答下。  一、获得可用字体  importpygame   print(pygame.font.get_fonts())  结果:  ['arial','arialblack','bahns...

    89542767 评论0 收藏0
  • 【代码笔记】Web-CSS-CSS Align

    一,效果图。二,代码。DOCTYPEhtml><html><head><metacharset="utf-8"><title>CSSAligntitle><style>body{margin:0;padding:0;} .container{position:relative;width:100%;} ...

    番茄西红柿 评论0 收藏0
  • Python学习笔记

    入坑 Python自从进入公司,到现在也有半年的时间。这半年的时间从 python 到入门到开发了几个小项目,类型涵盖了web应用 程序、爬虫程序 (scrapy),python脚本工具,自动化工具。对 python 语言也越来越熟悉,当然也有所感悟和总结。首先 Python 真的让语言成 了一个工具,入门代价很小,上手能够开发出小工具,可以更快体验到编程的乐趣。但是做到pythonic需要更多的...

    社区管理员 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<