欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > Jackson

Jackson

2024/10/25 23:31:54 来源:https://blog.csdn.net/howeres/article/details/142182188  浏览:    关键词: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 modelJsonNode rootNode = mapper.readTree(json);JsonNode appleNode = rootNode.path("a").path("b").path("c");// data-bindingApple apple = mapper.treeToValue(appleNode, Apple.class);
} catch (Exception e) {e.printStackTrace();
}

JSON Tree Model

  1. readTree
  2. path
  3. findValue
  4. findPath
  5. asText
  6. isEmpty
  7. isArray
  8. iterator (foreach)
  9. treeToValue

Data-binding method (注解方法)

@Data
@JacksonXmlRootElement(localName = "xBody")
public class Body {@JacksonXmlProperty(isAttribute = true)private String     version;@JacksonXmlProperty(localName = "total")@JsonInclude(JsonInclude.Include.NON_NULL)private Integer    total;@JacksonXmlProperty(localName = "item")@JsonProperty("item")@JacksonXmlElementWrapper(localName = "list")private List<Item> itemList;@JacksonXmlProperty(localName = "order")@JacksonXmlElementWrapper(useWrapping = false)private List<Order> orders;@Datapublic static class Item {@JacksonXmlPropertyprivate String name;}
}
  • 注解簇
    在这里插入图片描述在这里插入图片描述

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 结构中)
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com