如何使用 Jackson 将列表中的 JSON 单个项目<int, String) 映射到 String?

How to map A JSON single item from a list<int, String) to String with Jackson?

在一些传入JSON中有一个列表

"age" : 27,
"country", USA,
"fields": [
    {
      "id": 261762251,
      "value": "Fred"
    },
    {
      "id": 261516162,
      "value": "Dave"
    },
]

我知道我正在寻找的关键整数 [261762251]。

我想将其映射到 User 对象中的纯字符串字段 firstname 以及 JSON 中的其余底层字段。我尝试扩展 com.fasterxml.jackson.databind.util.StdConverter 并将注释 @JsonSerialize(converter=MyConverterClass.class) 添加到 User class 中的变量,但没有成功。

我的架构是这样的:

public class User {

   private String age;
   private String country;
   private String firstname; // this is the field in the list that needs converting

   // getters and setters
}

public class ApiClient{

   public User getUsers(){
      Response response;
      //some code to call a service
      return response.readEntity(User.class)
   }

}

实现此目标的最佳方法是什么?

您可以尝试如下操作:

class Tester
{
  public static void main(String[] args) throws Exception {
    String s1 = "{\"fields\": [ { \"id\": 261762251, \"value\": \"Fred\" }, { \"id\": 261516162, \"value\": \"Dave\" }]}";
    ObjectMapper om = new ObjectMapper();
    Myclass mine = om.readValue(s1, Myclass.class);
    System.out.println(mine);
  }
}


public class User {

   private String age;
   private String country;
   private String firstname; // this is the field in the list that needs converting
   @JsonProperty("fields")
   private void unpackNested(List<Map<String,Object>> fields) {
     for(Map<String,Object> el: fields) {
       if((Integer)el.get("id") == 261762251) {
          firstname = el.toString();
            }
          }
        }
   // getters and setters
}