gpt4 book ai didi

java - 在 spring 中从 json 字符串创建模型时验证模型

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:53 24 4
gpt4 key购买 nike

我正在 spring 中使用 json jackson 对象映射器从 json 字符串准备一个模型。

我的代码是

   ObjectMapper mapper = new ObjectMapper();
String empValue = mapper.writeValueAsString(employeeMap);
Employees employee = mapper.readValue(empValue, Employees.class);

在准备员工对象之前,我想验证 json,因为如果在准备模型时通过异常设置了任何不匹配的数据。我该怎么做?

最佳答案

您可以从异常中获取一些有值(value)的信息,主要来自 JsonMappingException类及其子类(在 com.fasterxml.jackson.databind.exc 包下)使用 getPathgetPathReference 方法

这里有两个例子:

public class ObjectMapperTest {
private ObjectMapper objectMapper;

@Before
public void setup() {
objectMapper = new ObjectMapper();
}

@Test
public void testWrongDataType() {
String personStr = "{\"age\":\"100Y\",\"firstName\":\"Jackson\",\"lastName\":\"Pollock\",\"gender\":\"M\"}";
try {
objectMapper.readValue(personStr, Person.class);
} catch (JsonMappingException jme) {
System.out.println(jme.getMessage());
if(jme instanceof InvalidFormatException) {
InvalidFormatException ife = (InvalidFormatException)jme;
System.out.println("Mapping failure on field:" + ife.getPathReference());
System.out.println("Expected type: " + ife.getTargetType());
System.out.println("provided value: " + ife.getValue());
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}

@Test
public void testUnrecognizedProperty() {
String personStr = "{\"gae\":\"100\",\"firstName\":\"Jackson\",\"lastName\":\"Pollock\",\"gender\":\"M\"}";
try {
objectMapper.readValue(personStr, Person.class);
} catch (JsonMappingException jme) {
System.out.println(jme.getMessage());
if(jme instanceof PropertyBindingException) {
PropertyBindingException pbe = (PropertyBindingException) jme;
System.out.println("Mapping failure on field:" + pbe.getPathReference());
System.out.println("UnExpected field: " + pbe.getPropertyName());
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}

输出将是

testUnrecognizedProperty:
========================
Unrecognized field "gae" (class Person), not marked as ignorable (4 known properties: "lastName", "gender", "firstName", "age"])
at [Source: {"gae":"100","firstName":"Jackson","lastName":"Pollock","gender":"M"}; line: 1, column: 9] (through reference chain: Person["gae"])
Mapping failure on field:Person["gae"]
UnExpected field: gae
testWrongDataType:
========================
Can not construct instance of java.lang.Integer from String value '100Y': not a valid Integer value
at [Source: {"age":"100Y","firstName":"Jackson","lastName":"Pollock","gender":"M"}; line: 1, column: 2] (through reference chain: Person["age"])
Mapping failure on field:Person["age"]
Expected type: class java.lang.Integer
provided value: 100Y

关于java - 在 spring 中从 json 字符串创建模型时验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com