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)
CodePudding user response:
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.
CodePudding user response:
You can do like this ...
class Information {
String queryName
String queryType
List<User> details
}
Does it work for you ? Leave me a comment
CodePudding user response:
Create a class of that structure and use ObjectMapper.readValue() method to deserialise it.
This can help: https://www.baeldung.com/jackson-object-mapper-tutorial#2-json-to-java-object
you can pass the json input in string format as well if it is not stored in a file explicitly.