JoonT
JoonT

Reputation: 1236

ObjectMapper convert string value(json format) to object

My api response seems like this

{
  "name": "jackson",
  "age": 33,
  "hobby_list": "[{\"name\":\"soccer\", \"priority\":2}, {\"name\":\"game\", \"priority\":1}, {\"name\":\"reading\", \"priority\":3}]"
}

I want to deserialize hobby_list string value as object.

class Person {
  @JsonProperty("name")
  private String name;

  @JsonProperty("age")
  private Integer age;

  @JsonProperty("hobby_list")
  private List<Hobby> hobbyList;
}

class Hobby(
  @JsonProperty("name")
  private String name;

  @JsonProperty("priority")
  private Integer priority;
)

It doesn't work as you know.

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<com.joont.domain.Hobby>` out of VALUE_STRING token

What is the best practice to solve the problem?
Annotation? Configure? Custom deserializer?

Upvotes: 0

Views: 6104

Answers (1)

Abinash
Abinash

Reputation: 301

You can convert them by registering custom deserializer as below:

public class PersonDeserializer extends JsonDeserializer<Person> {

    @Override
    public Person deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        ObjectCodec oc = jp.getCodec();
        JsonNode node = oc.readTree(jp);

        final Integer age = node.get("age").asInt();
        final String name = node.get("name").asText();
        final String hobbyListAsString = node.get("hobby_list").asText();

        ObjectMapper mapper = new ObjectMapper();
        // convert JSON array to List of objects
        List<Hobby> hobbyList = Arrays.asList(mapper.readValue(hobbyListAsString, Hobby[].class));

        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        person.setHobbyList(hobbyList);

        return person;
    }
}

and in pojo at root use annotation @JsonDeserialize(using = PersonDeserializer.class) so that above deserializer can be registered. Attaching reference below:

@JsonDeserialize(using = PersonDeserializer.class)
@Data
public class Person {
    @JsonProperty("name")
    private String name;

    @JsonProperty("age")
    private Integer age;

    @JsonProperty("hobby_list")
    private List<Hobby> hobbyList;
}

Then I was able to deserialize above hobby_list string to object

ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(content, Person.class);
System.out.println(person.getHobbyList());

Upvotes: 1

Related Questions