Jackson serialization. Force to wrap each field as an object

I know that a similar question has already been asked . But this decision does not suit me.

I have two POJOs with a fairly large number of fields:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Profile {

    @JsonProperty("userAttrs")
    private List<UserAttr> userAttrs;

}

and

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserAttr {

  @JsonProperty("ordercode")
  private String ordercode;

  @JsonProperty("transactionid")
  private String transactionid;

  @JsonProperty("receiptno")
  private String receiptno;

  // A lot more fields

Jackson produces JSON as expected:

"profile" : {
  "userAttrs" : [ {
    "ordercode" : 123,
    "transactionid" : 12345,
    "reference" : 123456789,
    "orderpaymenttypecode" : 1231341,
    ... more properties ...
  } ]
}

However, I need to wrap each property as a JSON object. Something like that:

"profile" : {
  "userAttrs" : [ 
    {"ordercode" : 123},
    {"transactionid" : 12345},
    {"reference" : 123456789},
    {"orderpaymenttypecode" : 1231341},
    ... more properties ...
  ]
}

I do not want to create separate POJOs for each field. Another way is to create a map for each field, but this is a bad decision.

Perhaps there are other ways to do this?

+4
source share
1 answer

Jackson, , , , JSON Java . , , , , JSON , , Java. , databind . , .

JSON, , , . , ObjectMapper mapper Profile profile, :

JsonNode profileRoot = mapper.valueToTree(profile);
ArrayNode userAttrs = (ArrayNode) profileRoot.get("userAttrs");
userAttrs.get(0).fields().forEachRemaining(userAttrs::addPOJO);
userAttrs.remove(0); // remove original multi-field object

- :

mapper.writeValueAsString(profileRoot)

JSON

+1

Source: https://habr.com/ru/post/1693417/


All Articles