杰克逊反序列化 - 包含ArrayList<T>

5

你好,

我正在尝试使用Jackson(与Jersey一起)消费一个生成JSON的REST服务(用.NET编写)。JSON包含可能的错误消息和对象数组。以下是Jersey日志过滤器生成的JSON示例:

{
    "error":null,
    "object":"[{\"Id\":16,\"Class\":\"ReportType\",\"ClassID\":\"4\",\"ListItemParent_ID\":4,\"Item\":\"Pothole\",\"Description\":\"Pothole\",\"Sequence\":1,\"LastEditDate\":null,\"LastEditor\":null,\"ItemStatus\":\"Active\",\"ItemColor\":\"#00AF64\"}]"
}

我有两个类来代表类型(外部的ListResponse):

public class ListResponse { 

    public String error;    
    public ArrayList<ListItem> object;  

    public ListResponse() { 
    }
}

以及(内部的ListItem):

public class ListItem {
    @JsonProperty("Id")
    public int id;      
    @JsonProperty("Class")
    public String classType;
    @JsonProperty("ClassID")
    public String classId;  
    @JsonProperty("ListItemParent_ID")
    public int parentId;    
    @JsonProperty("Item")
    public String item; 
    @JsonProperty("Description")
    public String description;

    @JsonAnySetter 
    public void handleUnknown(String key, Object value) {}

    public ListItem() {
    }
}

调用并返回JSON的类如下所示:
public class CitizenPlusService {
    private Client client = null;   
    private WebResource service = null;     

    public CitizenPlusService() {
        initializeService("http://localhost:59105/PlusService/"); 
    }

    private void initializeService(String baseURI) {    
        // Use the default client configuration. 
        ClientConfig clientConfig = new DefaultClientConfig();      
        clientConfig.getClasses().add(JacksonJsonProvider.class);                       

        client = Client.create(clientConfig);

        // Add a logging filter to track communication between server and client. 
        client.addFilter(new LoggingFilter()); 
        // Add the base URI
        service = client.resource(UriBuilder.fromUri(baseURI).build()); 
    }

    public ListResponse getListItems(String id) throws Exception
    {           
        ListResponse response = service.path("GetListItems").path(id).accept(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE).get(ListResponse.class);                                  
        return response;            
    }
}

这里重要的调用方法是 getListItems。在测试工具中运行代码,会产生以下结果:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
at [Source: java.io.StringReader@49497eb8; line: 1, column: 14] (through reference chain: citizenplus.types.ListResponse["object"])

请协助处理。

敬礼, Carl-Peter Meyer


你能解决这个问题吗? - varaprakash
如果您找到了一种改变.NET中JSON支持的方法,那么我的答案可能会对您有所帮助。http://stackoverflow.com/a/14760003/2022175 - Manolo
我认为这里的问题在于输入的JSON:'object'属性由包含JSON数组的字符串组成,但Jackson期望一个本地数组(不带包装的单引号)。 我目前也遇到了同样的问题...如果我找到解决方案,我会告诉你的 ;) - Philipp Maschke
3个回答

7
您可能缺少@JsonDeserialize属性,因为类型信息在运行时会丢失。此外,如果可以的话,应避免使用具体类来表示集合。
public class ListResponse { 

    public String error;

    @JsonDeserialize(as=ArrayList.class, contentAs=ListItem.class)
    public List<ListItem> object;  

}

4

你的问题是“object”属性值是一个字符串而不是一个数组!这个字符串包含了一个JSON数组,但是Jackson期望一个本地数组(没有包装引号)。

我也遇到了同样的问题,并创建了一个自定义反序列化器,它将把字符串值反序列化为所需类型的通用集合:

public class JsonCollectionDeserializer extends StdDeserializer<Object> implements ContextualDeserializer {

  private final BeanProperty    property;

  /**
   * Default constructor needed by Jackson to be able to call 'createContextual'.
   * Beware, that the object created here will cause a NPE when used for deserializing!
   */
  public JsonCollectionDeserializer() {
    super(Collection.class);
    this.property = null;
  }

  /**
   * Constructor for the actual object to be used for deserializing.
   *
   * @param property this is the property/field which is to be serialized
   */
  private JsonCollectionDeserializer(BeanProperty property) {
    super(property.getType());
    this.property = property;
  }

  @Override
  public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
    return new JsonCollectionDeserializer(property);
  }


  @Override
  public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    switch (jp.getCurrentToken()) {
      case VALUE_STRING:
        // value is a string but we want it to be something else: unescape the string and convert it
        return JacksonUtil.MAPPER.readValue(StringUtil.unescapeXml(jp.getText()), property.getType());
      default:
        // continue as normal: find the correct deserializer for the type and call it
        return ctxt.findContextualValueDeserializer(property.getType(), property).deserialize(jp, ctxt);
    }
  }
}

请注意,这个反序列化器也适用于值实际上是一个数组而不是一个字符串的情况,因为它会相应地委托实际的反序列化过程。
在你的例子中,你现在需要像这样注释你的集合字段:
public class ListResponse { 

    public String error;    
    @JsonDeserialize(using = JsonCollectionDeserializer.class)
    public ArrayList<ListItem> object;  

    public ListResponse() {}    
}

就是这样了。

注意:JacksonUtil和StringUtil是自定义类,但您可以轻松替换它们。例如通过使用new ObjectMapper()org.apache.commons.lang3.StringEscapeUtils


我喜欢这个解决方案,但在某些情况下会出现堆栈溢出的问题。 具体来说,我有一个 List<List<Integer>> 字段。 在这种情况下, 当询问内部列表时,return ctxt.findContextualValueDeserializer(property.getType(), property).deserialize(jp, ctxt); 会无限递归。我还没有深入研究它,但我认为这是因为传递的属性基于外部列表而不是内部列表。 - Michael Haefele

0

注册子类型已经可用啦!

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
public interface Geometry {

}

public class Point implements Geometry{
 private String type="Point";
  ....
}
public class Polygon implements Geometry{
   private String type="Polygon";
  ....
}
public class LineString implements Geometry{
  private String type="LineString";
  ....
}


GeoJson geojson= null;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.registerSubtypes(Polygon.class,LineString.class,Point.class);
try {
    geojson=mapper.readValue(source, GeoJson.class);

} catch (IOException e) {
    e.printStackTrace();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接