json使用介绍 json-schema使用介绍 json-rpc使用介绍

2016-01-10 21:56:00
admin
原创 3214
摘要:json使用介绍 json-schema使用介绍 json-rpc使用介绍

一、json使用介绍

1、官方文档https://www.json.org

2、在线编辑:https://jsoneditoronline.org

3、在线格式化:https://www.bejson.com

4、JSON:JavaScript Object Notation,一种轻量的数据交互格式;

5、JSON支持:object、array、string、number、true、false、null


jq处理数据:

1、入门帮助:https://jqlang.org/tutorial

2、参考手册:https://jqlang.org/manual

3、命令使用:jq [options] <jq filter> [file...]

4、拆包组包:.[]遍历对象和数组,{}组装对象,[]组装数组;

5、操作符号:逗号,同一个输入先后应用到逗号分隔的两个过滤器;

6、操作符号:管道,前一个过滤器的结果作为后一个过滤器的输入;

07、定义变量:as $identifier,定义变量不消耗输入,输入直接输出;

08、定义变量:变量存在作用域,使用圆括号定义作用域

09、内置函数:tojson转换为string,fromjson转换为json;

10、内置函数:map处理数组元素;


jq入门示例:

1、美化输出:jq '.' data.json

2、紧凑输出:jq -c '.' data.json

3、查询字段:jq '.name' data.json

4、递归查询:jq ' .. | .name?' data.json

5、查询数组元素:jq '.hobbies[0]' data.json

6、查询数组片段:jq '.hobbies[incl_idx:excl_idx]' data.json

7、查询数组长度:jq '.hobbies | length' data.json


jq高级示例:

1、正则匹配:jq 'map(select(.name | test("^张")))' data.json

2、条件查询:jq 'map(select(.name == "张三" and .age >= 18))' data.json

3、条件查询:jq '[.[] | select(.name == "张三" and .age >= 18)]' data.json

4、数据去重排序:jq 'unique_by(.name + (.age | tostring)) | sort_by(.name, .age)' data.json

5、数组转csv:jq -r '. as $myarr | ($myarr[0] | keys_unsorted), $myarr[] | [ .[] ] | @csv' data.json >output.csv

6、数组转tsv:jq -r '. as $myarr | ($myarr[0] | keys_unsorted), $myarr[] | [ .[] ] | @tsv' data.json >output.csv


二、json-schema使用介绍

1、官方文档:https://json-schema.org/learn

2、在线编辑:https://json.ophir.dev

3、在线转换https://transform.tools/json-to-json-schema

4、在线验证https://www.jsonschemavalidator.net

5、本地验证:https://github.com/python-jsonschema/jsonschema

6、安装依赖:pip install jsonschema


语法介绍:

1、类型定义:https://json-schema.org/understanding-json-schema/reference/type

2、关键字列表:https://json-schema.org/understanding-json-schema/keywords

3、入门帮助:https://json-schema.org/learn/getting-started-step-by-step

4、入门示例:https://json-schema.org/learn/miscellaneous-examples

5、版本列表:draft-05、draft-06、draft-07、2019-09、2020-12

6、关键字分类:结构关键字、注解关键字、验证关键字、条件关键字;

7、仅支持结构层次校验,无法表达元素之间的关系,无法进行语义校验;

8、{}和true表示接受任意有效的json,false表示不接受任意有效的json;

9、format适合标准格式字符串校验,pattern适合自定义格式字符串校验


高级特性:

1、支持常量,支持枚举,not否定条件

2、additionalProperties指定额外字段要求,

3、dependentRequired指定字段依赖关系,dependentSchemas指定更复杂的依赖校验

4、if-then-else根据字段的值条件验证、anyOf组合验证、allOf组合验证、oneOf组合验证;


三、json-rpc使用介绍

1、官方文档:https://www.jsonrpc.org/specification

2、json-rpc是一种无状态的轻量的远程调用协议;

3、json-rpc支持同步调用、消息通知、批量调用;


常用错误码:

-32700,Parse error
-32600,Invalid Request
-32601,Method not found
-32602,Invalid params
-32603,Internal error
-32002,Resource not found


四、json解析库对比

1、fastjson,阿里巴巴开源json解析库,漏洞太多,不推荐使用;

2、gson,谷歌开源json解析库,目前引用量最大,推荐使用;

3、jackson,Spring内置json解析库,目前引用量超过fastjson;


五、fastjson代码示例

1、解析可能抛异常需要捕获,因为底层是map,所以元素不允许重复;

2、如果需要元素按插入顺序排序,需要在初始化时指定;

3、null和空字符串解析不会抛异常,会返回null对象;

4、自定义浮点数序列化:JSONFilter.java


import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.*;
public class JSONTest {
public static void main(String[] args) {

String content = "{}";
JSONObject obj = JSON.parseObject(content);
System.out.println(obj); //{}

obj = JSON.parseObject("{\"name\":\"feinen\"}");
System.out.println(obj.get("name"));
System.out.println(obj.get("unknown")); //返回null
System.out.println(obj.getString("unknown")); //返回null
System.out.println(obj.getIntValue("unknown")); //返回0
System.out.println(obj.toString()); //输出{"name":"feinen"}

obj = new JSONObject(true); 
obj.put("name", "xiangfeineng");
obj.put("age", null);
obj.put("friends", new JSONArray());
SerializerFeature[] features = { SerializerFeature.WriteMapNullValue };
String msg = JSON.toJSONString(obj, features);
System.out.println(msg); //输出{"name":"xiangfeineng","age":null,"friends":[]}
}
}


六、gson使用详解

1、JsonElement包含4个子类:JsonObject、JsonArray、JsonPrimitive、JsonNull;

2、每种JsonElement都包含特定方法,使用isXX方法判断元素类型,使用getAs方法转换元素具体类型;

3、只有JsonPrimitive可以获取元素内容,getAsString和getAsInt都可以调用;

4、gson默认维护元素插入顺序;

5、JsonParser用于解析字符串到对象,解析null抛出异常,解析空字符串返回null;

6、Gson类解析字符串到POJO对象,或者将POJO对象转换成字符串,解析null和空字符串不会抛异常,会返回null;

7、Gson类解析字符串到POJO对象是利用反射机制,字符串不包含任何POJO属性时,返回的POJO对象属性值都是null;

8、时间序列化调用GsonBuilder的setDateFormat("yyyy-MM-dd HH:mm:ss"),或者使用类型适配器,后者优先级更高;

9、transient申明的字段不序列化,excludeFieldsWithoutExposeAnnotation表示使用@Expose注解的字段才会序列化;

10、@SerializedName用于指定序列化字段名;

11、setPrettyPrinting序列化格式更好看,serializeNulls序列化空对象,disableHtmlEscaping取消网页字符转义;

12、JsonElement.toString等价于new GsonBuilder().serializeNulls().disableHtmlEscaping().create().toJson;


序列化时间:

import java.lang.reflect.*;
import com.google.gson.*;
import java.util.*;
import java.text.*;
public class DateSerializer implements JsonSerializer<Date> {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(df.format(src));
}
}


反序列化时间:

import java.lang.reflect.*;
import com.google.gson.*;
import java.util.*;
import java.text.*;
public class DateDeserializer implements JsonDeserializer<Date> {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (Exception e) {
throw new JsonParseException(e);
}
}
}


GsonBuilder设置类型适配器:

registerTypeAdapter(Date.class, new DateSerializer())

registerTypeAdapter(Date.class, new DateDeserializer())

发表评论
评论通过审核之后才会显示。