Jackson-databind mapping JSON skip layer - java

I got a JSON response like this:
{
"status": "success",
"response": {
"entries": [
{
"id": 1,
"value": "test"
},
{
"id": 2,
"value": "test2"
}
]
}
}
And i want to map it with jackson-databind on an object like this:
public class Response {
#JsonProperty("status")
private String status;
#JsonProperty("response.entries")
private Collection<ResponseEntry> entries;
}
So i'm searching for an way to give #JsonProperty a path so it can skip the layer "response".

Welcome to Stack Overflow. You can define a wrapper class for your Collection<ResponseEntry> collection like below :
public class ResponseWrapper {
#JsonProperty("entries")
private Collection<ResponseEntry> entries;
}
The ResponseEntry class could be defined like below :
public class ResponseEntry {
#JsonProperty("id")
private int id;
#JsonProperty("value")
private String value;
}
Once defined these classes you can rewrite your old Response class like below :
public class Response {
#JsonProperty("status")
private String status;
#JsonProperty("response")
private ResponseWrapper responseWrapper;
}

You can flatten using the #JsonUnwrapped annotation.
You can have your classes like this
public class Response {
private String status;
private Collection<ResponseEntry> entries;
}
public class ResponseEntry {
#JsonUnwrapped
private Entry entry;
}
pubic class Entry{
private Integer id;
private String value;
}

Related

How to use #JsonUnwrapped in list of objects

I'm trying to deserialize a JSON object using Jackson annotation, but I can't deserialize it:
Is an array of a type "Deposito"
{
"depositos": [
{
"deposito": {
"id": "13168775373",
"nome": "Geral",
"saldo": "100000.0000000000",
"desconsiderar": "N",
"saldoVirtual": "100000.0000000000"
}
}
]
}
my java class:
#JsonUnwrapped
#JsonProperty(value ="depositos")
private List<Deposito> depositos;
my deposito class:
#JsonRootName(value = "deposito")
public class Deposito {
private String id;
private String nome;
private Double saldo;
private String desconsiderar;
private Double saldoVirtual;
}
You would need to add an additional class to your model:
public class DepositoMetadata {
private Deposito deposito;
}
Now you need to adjust your main java class (as you called it):
private List<DepositoMetadata> depositos;
Finally, you can remove #JsonRootName(value = "deposito") from your Deposito class.

Deserialising complex nested Json using Jackson

I am struggling to deserialise complex nested Json data into Java objects I think my class structure is wrong. Here is my Json data:
{
"resultsPerPage": 20,
"startIndex": 0,
"totalResults": 2,
"result": {
"dataType": "CPE",
"feedVersion": "1.0",
"cpeCount": 2,
"feedTimestamp": "2021-03-19T13:06",
"cpes": [
{
"deprecated": false,
"cpe23Uri": "cpe:2.3:o:microsoft:windows_10:1511:*:*:*:*:*:x64:*",
"lastModifiedDate": "2015-12-09T17:28Z",
"titles": [
{
"title": "Microsoft Windows 10 1511 64-bit",
"lang": "en_US"
}
],
"refs": [
{
"ref": "https://www.microsoft.com/en-us/",
"type": "Vendor"
}
],
"deprecatedBy": [],
"vulnerabilities": [
"CVE-2016-0174",
"CVE-2016-0171"
]
}
Here is the class I map the Json data to:
public class RESPONSE {
Result result;
}
class Result {
List<Cpes> cpes;
}
class Cpes {
String cpe23Uri;
List<Titles> titles;
List<String> vulnerabilities;
}
class Titles{
String title;
}
When I debug my code r in the below code is null and I think it's because my RESPONSE class isn't set up right.
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
RESPONSE r = mapper.readValue(response.getContent(), RESPONSE.class);
System.out.println(r);
Your object model should match the structure of the JSON you are trying to read. For example, it'll have to look something like the following:
public class Response {
private int resultsPerPage;
private int startIndex;
private int totalResults;
private Result result;
// Should include getters and setters
}
public class Result {
private String dataType;
private String feedVersion;
private int cpeCount;
private String feedTimestamp;
private CPE[] cpes;
// Should include getters and setters
}
public class CPE {
private boolean deprecated;
private String cpe23Uri;
private String lastModifiedDate;
private Title[] titles;
private Ref[] refs;
private String[] deprecatedBy;
private String[] vulnerabilities;
// Should include getters and setters
}
public class Title {
private String title;
private String lang;
// Should include getters and setters
}
public class Ref {
private String ref;
private String type;
// Should include getters and setters
}
Note that to keep the code sample short, I've omitted the getters and setters.
Edit: As Tugrul pointed out below, since fail on unknown property is disabled, it won't fail if there are missing fields in your model. The only issue is the missing getters and setters.
I also found another way to solve this issue for future reference.
I used a tree data structure to access my Json fields which means I can just declare a flat class:
public class Test {
private String cpe23Uri;
private String title;
private List<String> vulnerabilities;
public String getCpe23Uri() {
return cpe23Uri;
}
public void setCpe23Uri(String cpe23Uri) {
this.cpe23Uri = cpe23Uri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getVulnerabilities() {
return vulnerabilities;
}
public void setVulnerabilities(List<String> vulnerabilities) {
this.vulnerabilities = vulnerabilities;
}
}
I then mapped using a Tree
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode resultNode = mapper.readTree(response.getContent());
Test t = new Test();
t.setCpe23Uri(resultNode.get("result").get("cpes").get(0).get("cpe23Uri").textValue());

GSON Json Mapping for HashMap Nested Object

I have a json context like below:
{
"data": {
"details": {
"en-CA": {
"languageCode": "en-CA",
"isPrimaryLocale": false
},
"en-US": {
"languageCode": "en-US",
"isPrimaryLocale": true,
"languageDisplayName": "English (United States)",
}
}
}
}
To map it with GSON in java:
I created this classes:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private ResponseDetails details;
#Getter
public static class ResponseDetails
{
public HashMap<String, LocaleDetail> row = new HashMap<>();
}
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
When I try to map json to Java POJO class, HashMap doesn't work. Is there any suggestion?
To map it:
GSON.fromJson("...json", Type type...);
Just try to replace:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private Map<String, LocaleDetail> details;
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
Also json seems to be incorrect: "languageDisplayName": "English (United States)",
should be just "languageDisplayName": "English (United States)"
One more note: I believe you should have public fields or at least getters for them

Parse Response via rest template exchange

How to create a POJO class Of below mentioned JSOn Structure by a REST Service. Using RestTemplate.exchange i need to parse this in my java.class file and get approved_by value and use in java code. Below is the response structure:
{
"approval_rules_overwritten": true,
"rules": [
{
"id": 1,
"name": "Test",
"rule_type": "RuleTest",
"approvals_required": 2,
"approved_by": [
{
"id": 2,
"name": "ABC",
"username": "ABC_XYZ",
"state": "active",
}
],
"approved": false
}
]
}
Did you create a class representing this JSON ?
In quick in the same class file (different classes would be best in different files)
public class Response {
private Boolean approval_rules_overwritten;
private List<Rule> rules;
public static class Rule {
private Integer id;
private String name;
private String rule_type;
private Integer approvals_required;
private List<Approval> approved_by;
private Boolean approved;
public static class Approval {
private String id;
private String name;
private String username;
private String state;
}
}
}
Also remember to add getters and setters on each class.
Now you can do your classic request:
ResponseEntity<Response> = restClient.exchange(request, Response.class);
and you would get your response.
You now only have to build your rest template and also to catch exceptions that could be thrown from the exchange request.

Unable to deserialize JSON response into Java Objects

I know there are lots of queries on this topic but nothing has been helpful for me to resolve below issue
{
"_embedded": {
"customers": [
{
"id": 101,
"name": "John",
"city": "Ohio"
},
{
"id": 102,
"name": "Tom",
"city": "London"
}
]
}
}
for this I have created below Java objects:
#Data
public class Wrapper {
#JsonProperty("_embedded")
private Customers customer;
}
#Data
public class Customers {
#JsonProperty("customer")
private List<Foo> obj;
}
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo{
private int id;
private String name;
private String city;
}
Any help will be greatly appreciated.
You have some naming issues in your original question, but disregarding that, you could structure your classes according to the JSON to make it easier for both yourself and Gson.
Something like this would work:
public class JsonWrapper {
public Embedded _embedded;
}
public class Embedded {
public Customers customers;
}
public class Customers extends ArrayList<Foo>{ }
public class Foo{
public int id;
public String name;
public String city;
}
String json = "{\"_embedded\":{\"customers\":[{\"id\":101,\"name\":\"John\",\"city\":\"Ohio\"},{\"id\":102,\"name\":\"Tom\",\"city\":\"London\"}]}}";
JsonWrapper wrapper = new Gson().fromJson(json, JsonWrapper.class);

Categories

Resources