Как сопоставить отдельный элемент JSON из списка <int, String) в строку с Джексоном? - PullRequest
0 голосов
/ 11 января 2019

В некоторых входящих JSON есть список

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

Я знаю ключ int для того, что я ищу [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 голосов
/ 11 января 2019

Вы можете попробовать что-то вроде ниже:

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