假设我有以下Java类:
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Demo {
public int x;
public int y;
public List<Pair<Integer, Integer>> the_list;
}
Run Code Online (Sandbox Code Playgroud)
我想从以下json格式填充它:
{ "x" : 1,
"y" : 2,
"the_list" : [[1,2],[3,4]]}
Run Code Online (Sandbox Code Playgroud)
使用更快的xml
ObjectMapper mapper = new ObjectMapper();
Run Code Online (Sandbox Code Playgroud)
我可以在那里调用mapper.readTree(json)并填写我需要的一切.问题是我拥有的实际类(不是Demo)包含很多参数,我想从数据绑定功能中受益.
尝试平原:
mapper.readValue(json, Demo.class)
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of
org.apache.commons.lang3.tuple.Pair, problem: abstract types either need to be mapped to
concrete types, have custom deserializer, or be instantiated with additional type
information
Run Code Online (Sandbox Code Playgroud)
有没有办法将自定义解析与数据绑定混合?我查看了注释,但没有找到任何适合该目的的东西(我无法使用mixins来处理泛型,没有调用the_list的自定义setter可能是因为它是一个列表,JsonCreator不是一个选项,因为我没有写Pair类......).
说我上课了
class A {
public int x;
}
Run Code Online (Sandbox Code Playgroud)
然后可以解析有效的json,如下所示:
ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue("{\"x\" : 3}", A.class);
Run Code Online (Sandbox Code Playgroud)
如果字符串包含的数据超过解析对象所需的数据,是否有办法让解析器失败?
例如,我希望以下失败(成功)
A a = mapper.readValue("{\"x\" : 3} trailing garbage", A.class);
Run Code Online (Sandbox Code Playgroud)
我尝试使用带有JsonParser.Feature.AUTO_CLOSE_SOURCE = false的InputStream并检查流是否已被完全消耗,但这不起作用:
A read(String s) throws JsonParseException, JsonMappingException, IOException {
JsonFactory f = new MappingJsonFactory();
f.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
ObjectMapper mapper = new ObjectMapper(f);
InputStream is = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
try {
A a = mapper.readValue(is, A.class);
if(is.available() > 0) {
throw new RuntimeException();
}
return a;
} finally { …Run Code Online (Sandbox Code Playgroud)