2

I have got a JSON structure similar to below:

{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath1": {
      "Key": "Value"
    },
    "MyPath2": {
      "Key": "Value"
    }
  }
}

Within paths there could be a variable number of MyPath keys. I want to break this structure into something like below:

  • JSON 1:
{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath1": {
      "Key": "Value"
    }
  }
}
  • JSON 2:
{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath2": {
      "Key": "Value"
    }
  }
}

Is there any simple approach I can opt for this in Java?

3
  • You can delete part of json object like this delete arr.paths.MyPath2; So add your json to two var's, and from 1st remove 1st mypath, from 2nd remove 2nd my path. jsfiddle.net/h20voga5 That is what you need if i am not mistaken Commented Sep 9, 2016 at 8:39
  • Thanks for the response.. Good thought but the problem is i don't know how many Mypath will be there inside my paths .What i am thinking is Keep the JSON in one JSONObject and remove the paths key from the JSON and store it in a separate JSONObject and iterate over this 2nd object and add Mypath to 1st json. But problem with this is my JSONObject is not recognize MyPath1 and 2 and the Keyset values in my 2nd json.. Hope i didn't confuse you ;) Commented Sep 9, 2016 at 8:53
  • Oh i see, i have worked a lot with json where i dont know what is in and how many of objects are coming , you can check this question i answered where it automaticly generates html from json (stackoverflow.com/questions/38528886/…), you should just check for length of paths , and do while loop for it , and generate new JSON object where it does delete for each myPath (check for indexing and take objName with object.keys) that will have split paths. If you dont manage to do it , ill try to make JSfiddle after work :) Commented Sep 9, 2016 at 9:17

3 Answers 3

2

With Jackson, a popular JSON parser for Java, you can have the following:

String json = "{\"MyApp\":\"2.0\",\"info\":{\"version\":\"1.0.0\"},\"paths\":"
            + "{\"MyPath1\":{\"Key\":\"Value\"},\"MyPath2\":{\"Key\":\"Value\"}}}";

// Create an ObjectMapper instance the manipulate the JSON
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

// Create a list to store the result (the list will store Jackson tree model objects)
List<JsonNode> result = new ArrayList<>();

// Read the JSON into the Jackson tree model and get the "paths" node
JsonNode tree = mapper.readTree(json);
JsonNode paths = tree.get("paths");

// Iterate over the field names under the "paths" node
Iterator<String> fieldNames = paths.fieldNames();
while (fieldNames.hasNext()) {

    // Get a child of the "paths" node
    String fieldName = fieldNames.next();
    JsonNode path = paths.get(fieldName);

    // Create a copy of the tree
    JsonNode copyOfTree = mapper.valueToTree(tree);

    // Remove all the children from the "paths" node; add a single child to "paths"
    ((ObjectNode) copyOfTree.get("paths")).removeAll().set(fieldName, path);

    // Add the modified tree to the result list
    result.add(copyOfTree);
}

// Print the result
for (JsonNode node : result) {
    System.out.println(mapper.writeValueAsString(node));
    System.out.println();
}

The output is:

{
  "MyApp" : "2.0",
  "info" : {
    "version" : "1.0.0"
  },
  "paths" : {
    "MyPath1" : {
      "Key" : "Value"
    }
  }
}

{
  "MyApp" : "2.0",
  "info" : {
    "version" : "1.0.0"
  },
  "paths" : {
    "MyPath2" : {
      "Key" : "Value"
    }
  }
}

A new JSON will be created for each child of the paths node.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. If i want to explore more features of this jackson is there any good way to tht?
0

Try something on following lines..not perfect but a start..

  1. Convert the Json to Java object. You may need a java class or Pojo to map to it ( Unless you already have one). Var MyApp; var List list;

  2. Convert the Java object back to Json object in required format. Read each item

    • Always add the MyApp Iterate over the List list add to JsonObjectCollection
  3. Return all object and use them as needed

Comments

0

EDIT (Just noticed that its needed in Java , my bad ) --There might be easier way to do it but here is the solution i got. When you import your JSON save it to 2 vars , one will be used for creating new object. Create newArr for all new objects. I am looping through all paths and create newPath which is saved in newObjectsArray and then pushed to newArr. Then you can access all your objects through that array. If you have multiple myApps , you can make $each which will take upper data and create new json, and just move while loop inside it

jsFiddle : https://jsfiddle.net/h20voga5/2/

      var arr = {
 "MyApp":"2.0",
   "info":{  
      "version":"1.0.0"
   },
   "paths":{  
      "MyPath1":{
      "Key":"Value1"
      },
      "MyPath2":{
      "Key":"Value2"
      }
}
}

var newObjectArray = {
 "MyApp":"2.0",
   "info":{  
      "version":"1.0.0"
   },
   "paths":{  
      "MyPath1":{
      "Key":"Value1"
      },
      "MyPath2":{
      "Key":"Value2"
      }
}
}

var newArr = {'Data':[]}  
var length = Object.keys(arr.paths).length; 
var i = 0


while(i < length){
 newObjectArray.paths = {} 
  var objectKey = Object.keys(arr.paths)[i] // MyPath1, MyPath2...
  var objectValues = JSON.stringify(arr.paths[objectKey]) // {"Key":"Value1"} 
  var newPath = '{'+ objectKey + ':' +  objectValues+'}'

  newObjectArray.paths = newPath 
  newArr.Data.push(newObjectArray)


  i++
}


var countObjects = newArr.Data.length
alert(countObjects)
alert(JSON.stringify(newArr.Data[0])) // access your objects like this 

2 Comments

I understand the OP wants to do it in Java.
I just noticed it , well i gave him some logic to work on :) my bad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.