Extracting an array from a JSON object - java

I have a JSON Object of the following and I need to parse the path strings inside the web array into an new JSON array.
"taxonomy": {
"source": {
"master": {
"_id": "5000",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
"web": [
{
"_id": "6686",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
{
"_id": "7686",
"path": "/Appliances/Refrigerators/Bottom Freezers"
}
],
},
},
I have written till this but I'm not sure how to get all the path inside the web array.
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
if(!jsonTaxonomy.isNull("source"))
{
JSONObject jsonTaxonomySource= jsonTaxonomy.optJSONObject("source");
if(!jsonTaxonomySource.isNull("web"))
{
JSONArray jsonTaxonomySourceWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySourceWeb!=null && jsonTaxonomySourceWeb.length()>0)
{
//Got inside the array
}
}
}
}

Without providing you with a full answer, I'm convinced you'll be able to find your answer by debugging this method and stopping it at the most inner if(). You'll be able to of what jsonTaxonomySearsWeb consists and thus how to get its values.

Modify your code to something like this:-
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
JSONObject jsonTaxonomySource = jsonTaxonomy.optJSONObject("source");
if(jsonTaxonomySource!=null)
{
JSONArray jsonTaxonomySearsWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySearsWeb!=null)
{
// Traverse through your JSONArray and get each Object & extract path from it.
}
}
}

I am bit unclear about the question. But As per my understanding you want to parse the JSON if you want to do that in java then you can use GSON jar from google...you can also check simple example here Gson handle object or array

Try like this...
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length(); i++) {
JSONObject c = groups.getJSONObject(i);
String source = c.getString(TAG_SOURCE);
System.out.println("Checking ::"+source);
String lname = c.getString(TAG_PATH);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SOURCE, source);
map.put(TAG_PATH,path);
weblist.add(map); //weblist is your arraylist for both values
webpathlist.add(path); //webpathlist is your arraylist for path
}
List<String> newList = new ArrayList<String>();
newList.addAll(weblist);

Related

Null pointer observed while trying to fetch the object value from JSON array

I'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.

How to retrieve and update json array element without traversing entire json

I have a very complex json structure. It contains many array elements and those array elements contains other array elements and so on..
Please see below json tree structure.
Json Tree Structure-1 :
Json Tree Structure-2 :
As highlighted above in yellow, I want to update the value of "rdKey" field.
I wrote below code and it is perfectly working fine :
String json = "escaped string (as it's a big string, I can't put it here)";
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("responseMap")) {
JSONObject responseMap = jsonObj.getJSONObject("responseMap");
if (responseMap.has("ValueJson")) {
JSONObject valueJson = responseMap.getJSONObject("ValueJson");
if (valueJson.has("ticketBean_CM")) {
JSONObject ticketBean_CM = valueJson.getJSONObject("ticketBean_CM");
if (ticketBean_CM.has("addByGamma")) {
String addByGamma = ticketBean_CM.getString("addByGamma");
System.out.println(addByGamma);
if (addByGamma.equals("VCE")) {
if (responseMap.has("ScreenJson")) {
JSONObject screenJson = responseMap.getJSONObject("ScreenJson");
if (screenJson.has("sections")) {
JSONArray sectionArray1 = screenJson.getJSONArray("sections");
if (sectionArray1.length() > 0) {
JSONObject section0 = sectionArray1.getJSONObject(0);
if (section0.has("sections")) {
JSONArray sectionArray2 = section0.getJSONArray("sections");
if (sectionArray2.length() > 3) {
JSONObject section6 = sectionArray2.getJSONObject(3);
if (section6.has("sections")) {
JSONArray sectionArray3 = section6.getJSONArray("sections");
if (sectionArray3.length() > 1) {
JSONObject section8 = sectionArray3.getJSONObject(1);
if (section8.has("elements")) {
JSONArray elementsArray1 = section8
.getJSONArray("elements");
if (elementsArray1.length() > 0) {
JSONObject elements1 = elementsArray1.getJSONObject(0);
if (elements1.has("elements")) {
JSONArray elementsArray2 = elements1
.getJSONArray("elements");
if (elementsArray2.length() > 4) {
JSONObject elements2 = elementsArray2
.getJSONObject(4);
if (elements2.has("rdKey")) {
System.out.println(
elements2.getString("rdKey"));
elements2.put("rdKey",
"CircuitID(FullPartial)");
System.out.println(
elements2.getString("rdKey"));
System.out.println(jsonObj.toString());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
I want you guys to help me if there is any better solution for this. Can I do it without traversing the entire json object (till I find the concerned field) ? This solution will not work if json tree structure gets changes, it needs to be static as a success scenario of this code.
Please suggest better solution.
If you want to escape traversing of JSON then you can use JSONPointer, available in same org.json library.
E.g.:
String query = <json_pointer_query to element array>
JSONPointer pointer = new JSONPointer(query);
JSONObject elementsArrayJSON = (JSONObject) pointer.queryFrom(jsonObj);
elementsArrayJSON.put("rdKey","CircuitID(FullPartial)");
JSON Pointer query language can be referred in:
https://www.rfc-editor.org/rfc/rfc6901
Note:
JSON Pointer is pretty basic, it doesn't support wild card. So you need to be sure about element names, otherwise it would throw exception.
If you're flexible on what library to use, maybe the JsonPath will be useful for you.
You can update all "elements" with "rdKey" using the following code:
JsonPath.parse(json).set("$..elements[?(#.rdKey)].rdKey", "CircuitID(FullPartial)").json()

How to properly uplevel a json key in java? Why is the json not changing?

I have an array "myarray" like this:
[{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}]
How do I uplevel it properly? Using minimal-json, I do the following:
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
The last line when I print out my jsonArray, it looks as if nothing has changed whatsoever. What am I doing wrong? I want to end up with the following:
[{
name: John,
age: 18
computer_skills: 4
mile_runner: 2
}]
I tried using this: https://github.com/ralfstx/minimal-json. Alternatives are welcome. I want to not have to create a model object that contains key value pairs for every single key value in my object within "myarray". I am used to python where everything is simple to access and replace.
After some researching I found out that your json array is invalid, there are quotes missing on at least the keys (See why do you need the quotes). Look at the same code you used but with modified input for 'myarray':
String myarray = "[{\"name\":\"John\",\"age\":{\"years\":18},\"computer_skills\":{\"years\":4},\"mile_runner\":{\"years\":2}}]";
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
This code prints:
[{"name":"John","age":18,"computer_skills":4,"mile_runner":2}]
what is the expected result.

how to reverse the json array after response from webservice?

I am getting response this
{
"success": 1,
"message": "some message",
"data": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I am to get all response in json array like this
JSONObject js =new JSONObject(response);
routeJsonArray.=js.getJSONArray("data");
But I need to reverse all object which is inside data array .In other word when I get response and print commant_id "43906", "43905",
But I need I reverse that objects so that when I print it first give "43905","43906",
there is solution to iterate from i = routeJsonArray.length; i > 0; i-- But i don't want this.I want to store reverse array in another array ..
I try like this.
String [] routeStationString;
JSONArray localJsonArray = js.getJSONArray("data");
routeStationString = new String[localJsonArray.length()];
int k = 0;
for (int i = localJsonArray.length(); i > 0; i--) {
routeStationString[k++] = localJsonArray.getJSONObject(i);
}
System.out.println(routeStationString);
It gives error.?
My approach would be to create a Java Model representing a comment from your array and then proceed like this.
ArrayList<Comment> mList = new ArrayList<Comment>();
for(int i=0;i<routeJsonArray.length();i++){
//get the jsonobject based on the position
//retrieve its values
//create a new comment object and store it to the mList
}
Collection.reverse(mList);
You typically want to parse this array into a POJO, a model. So the idea would be to get a List<Comment> list for example and then you would be able to reverse that list through Collections.reverse(list) method.
How do you use the data from the JSON array? you still have to iterate it, plus remember the keys and everything. the most typical solution is to parse the JSON data into java objects.
JSONArray toReturn = new JSONArray();
int length = jsonArray.length()-1;
for(int i =length; i >= length;i--){
try {
toReturn.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong", Toast.LENGTH_SHORT).show();
}
}

Parsing JSON, not sure on how and when to use iterators (Android Platform)

I have this JSON to parse
{"files_informations": {
"row":{"value":"artist1"},
"row":{"value":"artist2"}
}
}
I would like to know how can I get the first value artist1 and then the second one artist2
This is what I am doing :
JSONObject myObject = jObject.getJSONObject("files_informations");
JSONObject rowObject = myObject.getJSONObject("row");
Iterator<JSONObject> rowIt = rowObject.keys();
while (rowIt.hasNext()) {
JSONObject tmp = rowIt.next();
Log.e("", tmp.getString("value"));
}
I got java.lang.classCastException for this JSONObject tmp = rowIt.next();
So there are my two questions :
Do I need to use iterators in this
case ?
How do one should use them ?
Edit :
Should the JSON looks like this ?
{"files_informations": [
"row":{"value":"artist2"},
"row":{"value":"artist1"}
]
}
rowIt.next() is "row" String in this case.
Refactor your JSON to this:
{"files_informations":
[ {"value":"artist2"},
{"value":"artist1"} ] }
Or even this:
{ "files_informations": [ "artist2", "artist1" ] }
and then use:
JSONArray artistsArr = myObject.getJSONArray("files_informations");
for (int i = 0; i < artistsArr.size(); i++) {
// first case
Log.d(TAG, artistsArr.get(i).getString("value"));
// Second case
Log.d(TAG, artistsArr.getString(i));
}
Iterators are not supported in JSONArrays, however you can convert them to plain Java arrays/lists if you really need it.

Categories

Resources