【问题标题】:How to deserialize a List of String to a single arg value class?如何将字符串列表反序列化为单个 arg 值类?
【发布时间】:2020-09-14 09:02:24
【问题描述】:

基本上,我总是想将我的 Id 类解包到父对象,但如果是 List,我不能使用 jackson 库中的 JsonUnwrapped Annotation。

@lombok.Value
public class Response {
  List<MyId> ids;
  // ... other fields
}

@lombok.Value
public class MyId {
  String id;
}

{
  "ids": ["id1", "id2"]
  "otherField": {}
}

使用 jackson-databind 2.11 的工作解决方案

@lombok.Value
public class MyId {
  @JsonValue
  String id;

  public MyId(final String id) {
    this.id = id;
  }
}

【问题讨论】:

    标签: java jackson deserialization jackson-databind


    【解决方案1】:

    您可以使用@JsonValue。来自docs

    标记注释,指示带注释的访问器的值(字段或“getter”方法[具有非 void 返回类型的方法,无参数])将用作实例序列化的单个值,而不是收集价值属性的常用方法。通常 value 是一个简单的标量类型(String 或 Number),但它可以是任何可序列化的类型(Collection、Map 或 Bean)。

    用法:

    @Value
    public class MyId {
        @JsonValue
        String id;
    }
    

    完整代码:

    public class JacksonExample {
    
        public static void main(String[] args) throws JsonProcessingException {
            ObjectMapper objectMapper = new ObjectMapper();
            List<MyId> myIds = new ArrayList<>();
            MyId id1 = new MyId("one");
            MyId id2 = new MyId("two");
            myIds.add(id1);
            myIds.add(id2);
            Response response = new Response(myIds, "some other field value");
            System.out.println(objectMapper.writeValueAsString(response));
        }
    }
    
    @Value
    class Response {
        List<MyId> ids;
        String otherField;
    }
    
    @Value
    class MyId {
        @JsonValue
        String id;
    }
    

    输出:

    {
      "ids": [
        "one",
        "two"
      ],
      "otherField": "some other field value"
    }
    

    【讨论】:

    • 谢谢,我试过了。 在我为类手动创建构造函数后,它按预期工作
    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多