首先,英语不是我的母语所以请原谅我有任何错误。 我正在尝试使用一个以JSON为对象服务的网络服务(我没有权力)。结果有点格式不正确:
[
[ #this is first object
{
"attribute1":"value1"
},
{
"attribute2":"value2"
}
],
[ # this is second object
{
"attribute1":"value1"
},
{
"attribute2":"value2"
}
]
]
因此,我尝试使用jersey client 2.22.1和jackson core 2.5.4将其反序列化为pojo。由于基本的杰克逊反序列化不是因为工作我已经创建了一个自定义反序列化器。
Pojo课程:
@JsonDeserialize(using = MyDeserializer.class)
public class Pojo {
private String attribute1;
private String attribute2;
*default constructor, getter and setters*
}
MyDeserializer类:
public class MyDeserializer extends JsonDeserializer<Pojo> {
@Override
public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Pojo pojoObj = new Pojo();
while (jParser.nextToken() != JsonToken.END_ARRAY) {
String fieldname = jParser.getCurrentName();
if ("attribute1".equals(fieldname)) {
jParser.nextToken();
pojoObj.setAttribute1(jParser.getText());
}
if ("attribute2".equals(fieldname)) {
jParser.nextToken();
pojoObj.setAttribute2(jParser.getText());
}
}
jParser.close();
return pojoObj;
}
}
泽西/杰克逊电话:
Client client = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class);
WebTarget webTarget = client.target("http://server/service/ressource").queryParam("param1", value);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
Response response = invocationBuilder.get();
list = Arrays.asList(response.readEntity(Pojo[].class));
但现在当我打电话给我时,我得到了:
java.lang.ArrayIndexOutOfBoundsException: 1054
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._skipWSOrEnd(UTF8StreamJsonParser.java:2732)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:652)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:149)
让我觉得杰克逊没有使用我的自定义解串器,或者我错过了什么。
答案 0 :(得分:0)
试试这段代码:
public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Iterator<JsonNode> iterator = node.iterator();
List<Pojo> pojos = new ArrayList<Pojo>();
while (iterator.hasNext()) {
JsonNode next = iterator.next();
pojos.add(
new Pojo(
next.get("attribute1"),
next.get("attribute2")));
}
return pojos;
}
答案 1 :(得分:0)
好的,我会给你答案,因为你制作了大部分代码,解决方案是:
public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Iterator<JsonNode> iterator = node.iterator();
JsonNode next = iterator.next();
String attribute1 = null
if (next.get("attribute1") != null) {
attribute1 = next.get("attribute1").asText();
}
next = iterator.next();
String attribute2 = null
if (next.get("attribute2") != null) {
attribute2 = next.get("attribute2").asText();
}
Pojo objPojo = new Pojo(attribute1,attribute2);
return objPojo;
}