在本教程中,我们将学习如何在 Spring Boot 应用程序中使用 ObjectMapper API 解析 JSON。
Jackson com.fasterxml.jackson.databind.ObjectMapper 类是解析和创建 JSON 的简单方法。 Jackson ObjectMapper 可以从字符串、流或文件中解析 JSON,并创建表示解析后的 JSON 的 Java 对象或对象图。
让我们看一个简单的例子:
package com.example.demojson;
import java.io.File;
import java.util.List;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean CommandLineRunner runner() {
return args -> {
String json = " {n" + " "
name ": "
Edmund lronside ",n" + " "
city ": "
United Kingdom ",n" + " "
house ": "
House of Wessex ",n" + " "
years ": "
1016 "n" + " }";
ObjectMapper mapper = new ObjectMapper();King c = mapper.readValue(json, King.class);
System.out.println(c);
};
}
}
在上面的示例中,我们解析一个简单的 JSON 字符串并将其转换为 Java 类:
package com.example.demojson;
public class King {
String name;
String city;
String house;
String years;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getHouse() {
return house;
}
public void setHouse(String house) {
this.house = house;
}
public String getYears() {
return years;
}
public void setYears(String years) {
this.years = years;
}
public King() {
super();
}
public King(String name, String city, String house, String years) {
super();
this.name = name;
this.city = city;
this.house = house;
this.years = years;
}
@Override public String toString() {
return "King [name=" + name + ", city=" + city + ", house=" + house + ", years=" + years + "]";
}
}
在以下示例中,我们解析 JSON 外部文件并将其转换为 Java 对象列表:
TypeReference < List < King >> typeReference = new TypeReference < List < King >> () {};
List < King > list = mapper.readValue(new File("/tmp/sample.json"), typeReference);
for (King k: list) System.out.println(k);
注意传递给 readValue() 的 TypeReference 参数。此参数告诉杰克逊读取 King 对象列表。
您还可以使用 ObjectMapper API 将 JSON 字符串生成到文件中,如下例所示:
ObjectMapper objectMapper = new ObjectMapper();
King king = new King("Edward the Martyr", "United Kingdom", "House of Wessex", "975-978");
objectMapper.writeValue(new File("target/king.json"), king);
如果 JSON 字符串包含其值设置为 null 的字段,则可以将 Jackson ObjectMapper 配置为失败:
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);
在上面的示例中,尝试将空 JSON 字段解析为原始 Java 字段时会出现异常。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.masterspringboot.com/develop-applications/rest-services/how-to-parse-json
内容来源于网络,如有侵权,请联系作者删除!