如何将字符串列表反序列化为单个arg值类?

问题描述

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

@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;
  }
}

解决方法

您可以使用@JsonValue。来自docs

标记注释,指示带注释的访问器的值(字段或“ getter”方法[具有非无效返回类型的方法,无args]的值)将用作实例序列化的单个值,而不是收集价值属性的常用方法。通常,值将是简单的标量类型(字符串或数字),但也可以是任何可序列化的类型(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"
}