Mark W
Mark W

Reputation: 5964

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

In some incoming JSON there is a list

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

I know the key int for what I am looking for [261762251].

I would like to map that to a plain String field firstname in the User object with the rest of the bottom level fields from the JSON. I have tried extending com.fasterxml.jackson.databind.util.StdConverter and adding the annotation @JsonSerialize(converter=MyConverterClass.class) to the variable in the User class with no luck.

My architecture is like this:

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

}

What is the best approach to achieve this?

Upvotes: 0

Views: 259

Answers (1)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

You can try something like below:

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
}

Upvotes: 1

Related Questions