I have id at the top level document and id at sub document. The subdocument id is not getting populated.
My JSON Document:-
{
"_id": "a392ec9c-4f5c-411a-8599-928c5ce6b18d",
"name": "polName",
"rules": [
{
"t": "TestRule",
"principals": [
{
"name": "Test Report",
"id": "Test Report",
"type": "PY"
},
{
"name": "Test Report1",
"id": "Test Report1",
"type": "SY"
}
]
}
]
}
Dto class,
@JsonInclude(Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class PolicyDto {
@JsonProperty("docId")
@JsonAlias({ "_id" })
private String id;
private String name;
private List<Rule> rules;
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(final List<Rule> rules) {
this.rules = rules;
}
public static class Rule {
private List<Principal> principals;
public List<Principal> getPrincipals() {
return principals;
}
public void setPrincipals(final List<Principal> principals) {
this.principals = principals;
}
}
public static class Principal {
private String name;
private String id;
private String type;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
}
}
Here, id inside principal is getting populated properly.
3
Answers
May I know how you’re using this DTO? i.e. is this being persisted or are you sending this as a response to a request? Also, a code snippet of how you’re populating the DTO would be appreciated.
I have tried the following snippet:
And the DTO:
The output:
The code works fine and the
id
you mentioned above seems to be populated properly. How are you trying to use this DTO? Can you elaborate more?In your Json on the "Rule" level there is a field "t" –
"t": "TestRule",
. In your classRule
you don’t have property "t" So, when I tried to parse your JSON I got an error complaining that field "t" was not known. So I added@JsonIgnoreProperties(ignoreUnknown = true)
to yourRule
class and then everything worked and all the fields got populated. Here is my code:Note that
JsonUtils
class is a thin wrapper overObjectMapper
class.JsonUtils
class comes with MgntUtils Open Source Java library written and maintained by me. Here is the Javadoc for JsonUtils class. The MgntUtils library could be obtained from Maven Central or from Github (including source code and Javadoc)