Skip to content
Advertisement

How can I deserialize it using Java?

I have a postgresql function that returns json:

{
  "query_name": "information1",
  "query_type": "information2",
  "details": [
    {
      "name": "Test01",
      "age": "35",
      "isUpdate": false
    }
  ]
}

How can I deserialize it using Java?

My POJO

@Getter
@Setter 
class Information {
String name;
String type;
List<User> details; 
}

@Getter
@Setter 
class User {
String name; 
Integer age;
Boolean isUpdate; 
}

I want to use ObjectMapper but I can’t do this)

Advertisement

Answer

Change your Information class to the following (mind the Jackson annotations to match JSON properties):

@Getter
@Setter 
class Information {
    @JsonProperty("query_name")
    String name;
    @JsonProperty("query_type")
    String type;
    List<User> details; 
}

And then you just need to use Jackson’s ObjectMapper to convert your JSON String to the corresponding objects as follows:

ObjectMapper objectMapper = new ObjectMapper();
String informationJsonFromDatabase = ""; // whatever logic you need here to get the String from the database
Information information = 
        objectMapper.readValue(informationJsonFromDatabase, Information.class);

I have doubts regarding Integer age;, because in your JSON it is represented as a String, so I am not entirely sure that Jackson is able to do the convertion. If it is not you will need to either change the property to String age; or create a custom deserializer for User class.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement