13

I've searched Stack Overflow before posting, but there were no solutions for Jackson.

Here is a server response:

{
  "ok": true,
  "result": [
    {
      "update_id": 489881731,
      //rest 
    },
    {
      "update_id": 489881732,
      //rest
    }
  ]
}

As you see property "result" is an array.

Now this is another response:

{
  "ok": true,
  "result": {
    "id": 211948704,
    "first_name": "ربات ادمین‌های تلگرام",
    "username": "tgAdminsBot"
  }
}

Here "result" is a single object.

This is my class I want to deserialize content to it. I wrote a custom deserializer for TObject of course:

public class Result
{
    private TObject[] result;
    private boolean ok;

    public void setOk (boolean ok) {//code}

    public void setResult (TObject[] result) {//code}


    public TObject[] getResult () {//code}

    public boolean getOk (){//code}
}

So I assumed in my class that "result" is an array of TObjects. Now what can I do? Is using @JsonProperty("result") for two fields which one is an array of TObjects and one is a single TObject OK?

If not what else can I do?

4

1 回答 1

17

如果DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY同时启用

{"result": []}

{"result": {}}可以解析为

class Result{
   List result;
}

文档链接

确定是否可以接受强制非数组(在 JSON 中)值与 Java 集合(数组、java.util.Collection)类型一起使用的功能。如果启用,集合反序列化器将尝试处理非数组值,就好像它们具有“隐式”围绕 JSON 数组一样。此功能旨在用于兼容性/互操作性的原因,与在数组中只有一个元素的情况下省略 JSON 数组的包(例如 XML 到 JSON 转换器)一起使用。默认情况下禁用该功能。

演示如何将其用于 OP 输入 json 和 POJO:

ObjectMapper mapper = new ObjectMapper()
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Result result = mapper.readValue(Result.class;

@JsonFormat如果您出于某种原因不喜欢映射器版本,可以与上述类或字段一起使用

@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)

PS。关于此问题的其他 SO 问题:LINK

于 2016-05-12T00:51:09.613 回答