Iterating the JSON object using Java not working exactly - java

I'm trying to get one JSON object and iterate it. In this case it should iterate only once because I'm having only one complete JSON object, if it has multiple, it should iterate multiple times. But rather it shows the system.out.println string twice. I don't understand whats wrong in this code?
String str = "{\"userId\":\"1234\",\"businessPrimaryInfo\":{\"53bd2a4\":{\"businessSpecificInfo\":{\"businessType\":\"Manufacturing\",\"tradingPlace\":\"Hyderabad\"}},\"53bd2a4e\":{\"businessSpecificInfo\":{\"businessType\":\"Milling\",\"tradingPlace\":\"Mumbai\"}}}}";
JSONObject jsonObj = new JSONObject(str);
Iterator<String> keys = jsonObj.keys();
// Iterate all the users.
while (keys.hasNext()) {
String key = keys.next();
try {
// If the user has Business primary info as JSON object.
if (jsonObj.has("businessPrimaryInfo")) {
JSONObject jsonBizPrimaryInfo = jsonObj
.getJSONObject("businessPrimaryInfo");
System.out.println("Object is:" + jsonBizPrimaryInfo);
}
} finally {
}
}
Please have a look and let me know where I'm doing wrong.

The two keys that are causing your loop to iterate twice are: userId and businessPrimaryInfo. But you ask the main JSON object if it has a businessPrimaryInfo key. Which it has for every iteration.
What you need to do is check that the current key is businessPrimaryInfo.
Or, you can just ask the primary object if it has a businessPrimaryInfo key, and if so, ask for that child object.

Related

JSON how to access entries within entries?

Consider this:
Dogs {
001{
age{
5
}
}
002{...}
...
}
I'd like to ultimately find the age of a dog, however, I do not know how many ids there are, and which is going to be the parameter.
So how exactly can I read this JSON?
I assume it would look something like this jsonObj.dogs.(desiredDog.getID()).age, yet getID would yield either an integer or a string, and I don't know if Java would understand I'm trying to conjure up a key.
I am assuming you're using org.json.simple. All you need to do is iterate over the keys of Dog objects, obtain them and then extract their age.
JSONParser parser = new JSONParser();
JSONObject rootObj = (JSONObject) parser.parse(yourJson);
for(Object key : rootObj.keySet()){
JSONObject dog = (JSONObject) object.get(key);
int age = (int) dog.get("age");
}

how to check if all JSON values are of type string

What I want to achieve is to check if all the values of a JSON object is of type String. I have read about JSONObject's getString method and thought about making a while-loop that iterates through a JSON object, but I think this will be an inefficient solution to the problem.
Is there a library that can achieve value-type checking for all values of a JSON object? (ex. all JSON values are String, Integer, boolean, etc.)
Any advice/tip is greatly appreciated.
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof String) {
// do something with jsonObject here
}
}

How to extract a json object from a json array by name in java?

I'm recieving JSON from the Google Directions API and the request is like the one shown here (under Directions Responses -> Json Output) link
I don't know how to extract a particular entry from within a json array. Basically what I need is the JsonArray equivalent of JSONObject method get(String key) where you can get the entry mapped to a specific key. However, the JSONArray has no such method, and seems to only support the retrieval of info through a specific index. This is all well and good, but the google directions reponses' contents can vary - so I need a way to either find a specific key-value pairing, or loop through the entire array and have a way to check the value of the key. I could even find a way to determine the key that a JSONObject was mapped to. Any suggestions? Ex: How would you extract the distance JSONObject out of the JSONArray legs?
Edit: This is where I am stuck: Refering the the JSON example output here... I am trying to get the value of the "overview_polyline" entry within the "routes" json array. Since I cannot access the "overview_polyline" entry simply by referring to its name, I must loop through the array until I get to that entry. But how would I know when I got to that entry? Yes, perhaps I could check if the JSONObject representation of the entry had a "points" key, but that isn't necessarily exclusive to the "overview_polyline" entry. Also, I cannot simply get the (array.length() - n) entry because the number of entries returned in the array may vary. In short, it seems to me that I need a way to check the name ("overview_polyline") of each JSONObject to reliably be able to extract that information.
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++)
{
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null)
{
//How do I determine if this object is the "overview_polyline"
//object?
}
}
The route is a JSONArray of JSONObject, so you have to do it this way:
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++) {
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null) {
JSONObject polyline = obj.optJSONObject("overview_polyline");
}
}

Json can work with sets

My question is how JSON works with serializing Sets because in my example , "propertyItems.getAddress().getCity().getProvinces().getCities()" is set of cities (Set) , i am iterating on it through for-each loop and putting it into json array. However it contains two cities i.e. MONTREAL and QuebecCity. But my url is only showing me "MONTREAL". Why its so? Json can't serialize sets provided to it?
JSONArray jarray = new JSONArray();
try {
JSONObject obj = new JSONObject();
for(Cities city:propertyItems.getAddress().getCity().getProvinces().getCities()){
obj.put("City Name",city.getCityname());
}
jarray.put(obj);
catch (JSONException e) {
logger.error(Constants.METHOD_INSIDE_MESSAGE +"getAuthors",e);
}
return jarray.toString();
}
** URL Output:** City Name :Montreal
The JSON specification states
The names within an object SHOULD be unique.
In the JSON parser/generator implementation you are using, ie. JSONObject, it seems the keys are unique. Every time you put an object with the same key, it overwrites the one added before it. Regardless of how many you put, the JSONObject will only contain one entry.

When JsonObject's keys are iterated they aren't in the same order as in the response from the server

I have a very large response from server of JSON string. I converted it to JSON object and then get the keys and iterate it.
The problem is that when I iterate it isnt in the same order as in response from server.
Next then I apply another method by adding all the keys in List<String> and the sort it and then get the iterator of that but still it isn't as I required (as in response).
Code example is here:
JSONObject jsonObject = new JSONObject(responseString);
Iterator<String> myIter = jsonObject.keys();
List<String> sortKey = new ArrayList<String>();
while(myIter.hasNext()){
sortKey.add(myIter.next());
}
Collections.sort(sortKey);
The order of the keys of a JSON object is not supposed to be meaningful. If you want a specific order, you should use an array, not an object.
Your Java code sorts the keys alphabetically. There is no way to get the initial ordering of the keys in the object.
Reference 1:
The order of the keys is undefined
Reference 2:
An object is an unordered set of name/value pairs
You can use Sorted map to put keys and values into. Something like this
public static List listFromJsonSorted(JSONObject json) {
if (json == null) return null;
SortedMap map = new TreeMap();
Iterator i = json.keys();
while (i.hasNext()) {
try {
String key = i.next().toString();
JSONObject j = json.getJSONObject(key);
map.put(key, j);
} catch (JSONException e) {
e.printStackTrace();
}
}
return new LinkedList(map.values());
}
I came across this similar problem while working on section in my android app which displays a list of 1024+ websites alphabetically. Since the json traversal was not in sorted order , I just inserted the json values during traversal into a table ( I m using list adapters in my app) and obtained sorted list of websites with cursor.
So if you are saving what you are fetching from server, you can just query your database to sort the values in the order your want.

Categories