0

i have list of masters that have two fields that are name and rating and after serialization to array node i need to add one more field to each object for example i have json

[{"masterName":"Bruce","rating":30},{"masterName":"Tom","rating":25}]

and i have list of servisec in json format that look like that

[{"masterName":"Bruce","services":["hair coloring","massage"]},{"masterName":"Tom","services":["hair coloring","haircut"]}]

i need it to looks something like that

[{"masterName":"Bruce","rating":30,"services":"hair coloring,massage"},{"masterName":"Tom","rating":25,"services":"hair coloring, haircut"}]

How can do it by using jackson?

DozezQuest
  • 179
  • 7
  • 1
    Jackson is just for handling json, if you're aggregating data, deserialize everything into java objects, process your data and serialize it again. – svarog Jun 09 '21 at 05:23

1 Answers1

0

I would approach it this way. Since you want to use Jackson.

First of all, I would extend the Master class by adding the services (which seems to be an array with Strings).

So the class would look something like this:

    public class Master
    {
        private String masterName;
        private int rating;
        private List<String> services = new ArrayList<>(); // THE NEW PART
        
        // Whatever you have else in your class
    }

Then you could get your JSON array, I am supposing that it comes as a String for simplicity. Serialize this array in an array with Master objects and then you can add the services as said above.

e.g.

    String yourJsonString = "[{\"masterName\":\"Bruce\",\"rating\":30},{\"masterName\":\"Tom\",\"rating\":25}]";
    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    List<Master> theListOfMasters = new ArrayList<>();

    // Read them and put them in an Array
    Master[] mastersPlainArr = mapper.readValue(yourJsonString, Master[].class);

    theListOfMasters = new ArrayList(Arrays.asList(mastersPlainArr));

    // then you can get your masters and edit them..

    theListOfMasters.get(0).getServices.add("A NEW SERVICE...");

    // And so on...

    // Then you can turn them in a JSON array again:

    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(theListOfMasters);
Renis1235
  • 4,116
  • 3
  • 15
  • 27