gpt4 book ai didi

java - 如何在 Jackson JsonMappingException 中获取 JSON 对象的路径

转载 作者:行者123 更新时间:2023-11-30 05:40:58 24 4
gpt4 key购买 nike

我正在使用 Jackson 反序列化这种形式的 JSON:

{
"foo" : { "bar" : "baz" }
}

jackson 代码可能如下所示:

  @JsonCreator
public class MyProxy {
@JsonProperty("foo") final FooProxy foo;
}

public class FooProxy {
@JsonProperty("bar") final String bar;
}

想象一下该 API 的使用者创建了如下所示的无效 JSON:

{
"foo" : { "bar" : 1 }
}

但是,在这种情况下,我收到 MismatchedInputException 并且错误如下所示:

Cannot construct instance of MyProxy (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)

当我检查 MismatchedInputException 并调用 ex.getPathReference() 时,我得到:

FooProxy["bar"]->java.lang.Object[0]

我希望能够将损坏值的路径返回给用户,而无需引用底层 Java 类。

"foo.bar must be an Object."

如何返回带有 JSON 路径的错误消息,并删除对 Java 实现的任何引用?

最佳答案

类似这样的事情应该可以做到:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;


public class DeserializationErrorTest {

@Test
void testDeserializeWrongInput() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue("{\"foo\" : { \"bar\" : \"not-int\" }}", MyProxy.class);
} catch (MismatchedInputException e) {
throw remapMismatchedInputException(e, RuntimeException.class);
}
}

private <T extends Exception> T remapMismatchedInputException(final MismatchedInputException e, Class<T> exClass) {
try {
final String fieldName =
e.getPath().stream().map(JsonMappingException.Reference::getFieldName).collect(Collectors.joining("."));
return exClass.getConstructor(String.class).newInstance(fieldName + " must be of type " + e.getTargetType().getSimpleName());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException pE) {
throw new IllegalArgumentException("Cannot instantiate exception class " + exClass.getSimpleName());
}
}

static class MyProxy {
@JsonProperty("foo") final FooProxy foo;

@JsonCreator
public MyProxy(@JsonProperty("foo") final FooProxy pFoo) {foo = pFoo;}
}

static class FooProxy {
@JsonProperty("bar") final Integer bar;

@JsonCreator
public FooProxy(@JsonProperty("bar") final Integer pBar) {bar = pBar;}
}
}

将会导致:

java.lang.RuntimeException: foo.bar must be of type Integer

关于java - 如何在 Jackson JsonMappingException 中获取 JSON 对象的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55681300/

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