0
votes

I'm reading a JSON string that has a dynamic structure. The JSON may have an array of object and object or both or only key values.

I tried to traverse through all the possibilities, I know, to read.

I need to read entire string without missing any node/key pairs.

Here's an example for the JSON:

{
  "cityId": {
    "city": "Old Delhi",
    "cityId": "CTY2",
    "stateId": "STE1",
    "statusId": "STA1",
    "userId": "ONB1"
  },
  "emailId": "[email protected]",
  "firstName": "Udit",
  "lastName": "R",
  "password1": "xxxxxx",
  "password2": "xxxxxx",
  "statusId": {
    "status": "ACTIVE",
    "statusId": "STA1"
  },
  "userId": "ONB2",
  "userInfoId": {
    "deptId": {
      "deptId": "DPT2",
      "deptName": "HR",
      "statusId": "STA1",
      "userId": "ONB1"
    },
    "roleId": {
      "roleId": "RLE2",
      "roleName": "Member",
      "statusId": "STA1",
      "userId": "ONB1"
    },
    "statusId": {
      "status": "ACTIVE",
      "statusId": "STA1"
    },
    "userId": "ONB2",
    "userInfoId": "UIN2"
  }
}

My current Java method:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.io.IOException;
import java.util.Iterator;
import org.json.JSONObject;

// Omittded class definiton, just the method
public void getRSDataFromMethodTwo(String url) throws IOException {
    // Initiate client and do JSON request
    Client client = Client.create();
    WebResource webResource = client.resource(url);        
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) 
    {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }
    String output = response.getEntity(String.class);
    System.out.println("Response===get=" + output);

    // Parse JSOn
    JSONObject json = new JSONObject(output);
    Iterator<String> iterator = json.keys();               

    System.out.println("Fields:");
    while (iterator.hasNext()) 
    {
        String x = iterator.next().toString();
        System.out.println(" Keys " + x);                        
    }

    iterator = json.keys();
    while (iterator.hasNext()) 
    {
        String key = iterator.next();
        System.out.println(key + " : " + json.get(key));
        if (json.get(key).toString().startsWith("{")) 
        {                
            JSONObject childJson = new JSONObject(json.get(key).toString());                               
            Iterator<String> childIterator = childJson.keys();
            if (childIterator.hasNext()) 
            {                                        
                while (childIterator.hasNext()) 
                {
                    String chKey = childIterator.next();
                    System.out.println("Child Key "+chKey+ " : "+childJson.get(chKey));                        
                }
            }
        }            
    }
}

And the output:

Info:   firstName : Udit
Info:   lastName : Ranjan
Info:   statusId : {"statusId":"STA1","status":"ACTIVE"}
Info:   Child Key statusId : STA1
Info:   Child Key status : ACTIVE
Info:   emailId : [email protected]
Info:   password2 : xxxxxx
Info:   cityId : {"statusId":"STA1","city":"Old Delhi","stateId":"STE1","cityId":"CTY2","userId":"ONB1"}
Info:   Child Key statusId : STA1
Info:   Child Key city : Old Delhi
Info:   Child Key stateId : STE1
Info:   Child Key cityId : CTY2
Info:   Child Key userId : ONB1
Info:   password1 : b2b123
Info:   userId : ONB2
Info:   userInfoId : {"statusId":{"statusId":"STA1","status":"ACTIVE"},"roleId":{"statusId":"STA1","roleId":"RLE2","roleName":"Member","userId":"ONB1"},"deptId":{"deptName":"HR","statusId":"STA1","deptId":"DPT2","userId":"ONB1"},"userId":"ONB2","userInfoId":"UIN2"}
Info:   Child Key statusId : {"statusId":"STA1","status":"ACTIVE"}
Info:   Child Key roleId : {"statusId":"STA1","roleId":"RLE2","roleName":"Member","userId":"ONB1"}
Info:   Child Key deptId : {"deptName":"HR","statusId":"STA1","deptId":"DPT2","userId":"ONB1"}
Info:   Child Key userId : ONB2
Info:   Child Key userInfoId : UIN2

Edit- as I am not able to read through nested object like child key deptId, since it is dynamic string I don't know which object is having nested object.

1
What is actually missing from that output? What's wrong about it?Seth
I would highly recommend using Jackson. With this you can design a wrapper POJO of what can come in and it will automaticall deserialize the whole dynamic json to a POJO you can interact with.Nico

1 Answers

0
votes

Have a look at using the Jackson library with the @JsonAnySetter http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html