jackson配置和解析JSON
jackson是Java语言中最通用的JSON解析库
Maven中添加jackson依赖
1、打开目录下的pom.xml
2、在project中加入以下代码
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
</dependencies>
3、在IDEA编辑器下,右击选择Maven,点击Reimport,即可完成
基本使用
可以参考别人写的一篇博客
https://blog.youkuaiyun.com/u011054333/article/details/80504154
核心的是使用ObjectMapper类进行对JSON的处理
readValue可以从文件或者字符串中获得JSON对象并转换为Java对象
下面举一些例子
读取
可以用Map来接收,格式上是一一对应的
ObjectMapper objectMapper = new ObjectMapper();
Map map =objectMapper.readValue(
new File("./data.json"),Map.class
);
也可以用List来接收,但需要进行一些处理。
List<DemoClass> redPackList =
objectMapper.readValue(file,
new TypeReference<List<DemoClass>>() {
});
也可用String
String jsonContent = objectMapper.writeValueAsString(DemoClass);
objectMapper.readValue(jsonContent,DemoClass.class);
写入
objectMapper.writeValue(file, demoClassList);