javajsonrandommergedynamicobject

read dynamic json files in java and merge them


I am struggling with json-parsing in java.
Is there a possibility to generate a representation of a random, not standardised json file in java? I tried to use gson but I didn't really understood if and how that might be possible.

So the jsonFile could look like this:

{ 
 "id":16875,
 "position":[1,2,5,7],
 "metadata":{
     "color":"blue",
     "id": "84779jh",
     "more":{ "some":"randomdata","absolutly":"noStructure"}
}

any key-value pairs are possible and the json file can be nested as much and as deep as it wants to. I need to get something like a java object out of it to be able to merge it with another json file. I just need the metadata part, the rest can be ignored.

So anybody any ideas how I could make that work? I would appreciate any helps :)

the json above merged with (this is the parent node, so we keep his id and position and just merge the metadata)

  { 
   "id":16zut,
   "position":[1,2,5,7],
   "metadata":{
     "color":"green",
     "id": "84ergfujh",
     "more":{ 
        "some":"randomdata",
        "even":"more",
        "absolutly":"noStructure"
     },
     "tags":[1,2,3,4,6,8,f7,h,j,f]
   }

would be:

  { 
   "id":16zut,
   "position":[1,2,5,7],
    "metadata":{
    "color":["blue", "green"],
    "id": ["84779jh","84ergfujh]",
    "more":{ "some":"randomdata","absolutly":"noStructure","even":"more"}
    "tags":[1,2,3,4,6,8,f7,h,j,f]
  }

Thanks in advance and have a nice day.


Solution

  • I got my problem solved and i am grateful thank you guys helped me with it. So let me share:

    I read the 2 jsons both as a tree (i am using Jackson):

       ObjectMapper mapper = new ObjectMapper();
       JsonNode parent = mapper.readTree(new File(path)); 
       JsonNode child= mapper.readTree(new File(path)); 
    

    And the merge logic isn't done yet but the basic concept is:

     Iterator<String> pIt = parent.fieldNames();
        while(pIt.hasNext())
        {
            String tempkey = pIt.next();
    
            if(child.path(tempkey) != null)
            {
                merged.put(tempkey,child.path(tempkey));
    
            }
            else{
                    merged.put(tempkey,parent.path(tempkey) );
            }
    
        }
    
        try {
            String jsonString = mapper.writeValueAsString(merged);
            System.out.println(jsonString);
        } catch (JsonProcessingException e) {...}
    

    If you think it is a dumb solution, i am open for other ideas...
    But i think it might work for my needs.

    greetings and thanks :)