如何从列表<int,string)=“”到=“” string =“”与=“” jackson映射JSON单个项目?=“”

时间:2019-01-11 12:24:54

标签: java jackson jackson-databind

=“ “

在某些传入的JSON中,有一个列表

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

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

我想将其映射到firstname对象中的纯字符串字段User,并使用JSON中的其他最低层字段。我尝试扩展com.fasterxml.jackson.databind.util.StdConverter并将注释@JsonSerialize(converter=MyConverterClass.class)添加到User类中的变量中,但是没有运气。

我的架构是这样的:

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)
   }

}

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

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

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
}