![](/img/trans.png)
[英]Unable to deserialize json array to class object using jackson fasterxml in scala
[英]FasterXML Jackson: Deserialize json strings that are different?
我和Jackson有问题,我可以收到以下两个JSON字符串:
{"resp":{}}
这是另一个回应。
{"resp":{"seg":[]}}
这是我正在使用的代码,但它打破了:
for(JsonNode node : json.get("resp").get("seg")) {
//...
}
不幸的是我得到一个错误,因为我收到的一些字符串没有“seg”字段。 怎么会去反序化呢?
你可以使用数据绑定;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FooTest {
private static final String NO_SEG = "{\"resp\":{}}";
private static final String WITH_SEG = "{\"resp\":{\"seg\": []}}";
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
public void noSeg() throws IOException {
final Bar bar = MAPPER.readValue(NO_SEG, Bar.class);
assertTrue(bar.getResp().isEmpty());
}
@Test
public void withSeg() throws IOException {
final Bar bar = MAPPER.readValue(WITH_SEG, Bar.class);
assertFalse(bar.getResp().isEmpty());
assertTrue(bar.getResp().get("seg").isEmpty());
}
private static class Bar {
@JsonProperty("resp")
private Map<String, ArrayList<String>> resp;
public Bar() {
}
public Map<String, ArrayList<String>> getResp() {
return resp;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.