Jackson

Jackson

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson}</version>
</dependency>

Json 读取有两种模式:

  1. JSON Tree Model
    1. 树的根代表整个JSON文档。
    2. 树中的每个节点对应于JSON值,如对象、数组、字符串、数字、布尔值或空值。
    3. 节点可以有子节点,表示嵌套的JSON结构。
  2. Data-binding method
    1. 直接转换成对象
try {
    ObjectMapper mapper = new ObjectMapper();
    // tree model
    JsonNode rootNode = mapper.readTree(json);
    JsonNode appleNode = rootNode.path("a").path("b").path("c");

    // data-binding
    Apple apple = mapper.treeToValue(appleNode, Apple.class);
} catch (Exception e) {
    e.printStackTrace();
}

Spring 自带 Json 工厂

JsonNode 转 Map

使用 springboot 提供的 json 转换工具 org.springframework.boot.json.JsonParserFactory

private static Map<String, Object> setAllValue(JsonNode source, BillSubData target) {

    JsonParser jsonParser = JsonParserFactory.getJsonParser();

    Map<String, Object> sourceMap = jsonParser.parseMap(source.toString());
    for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
        target.set(entry.getKey(), entry.getValue());
    }
    return sourceMap;
}

JsonNode 判断 null

// Method similar to #findValue(str), 
// but that will return a "missing node" instead of null if no field is found. 
// Missing node is a specific kind of node for which isMissingNode returns true;
JsonNode node = jsonNode.findPath("key"); // 必须使用 findPath 获取 JsonNode 对象

if (node.isNull()) {
    // 节点为空
}
if (node.isEmpty()) {
    // 节点为空(null、空对象、空数组)
}
if (node.isMissingNode()) {
    // 是否为缺失节点(不存在于 JSON 结构中)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值