How to fetch values of sub array inside the main array? - java

I am new at programming. I just want to ask if there is a possible way of fetching values of sub arrays from main array? I have this problem of fetching the values from sub array entitled "subresult". I have code of getting values from an array but it seems that it only gets the outer array and disregard the inner array. It is sad that I have no luck in this. Please respect my question because I'm just a beginner. Hoping an answer from you guys. Thank you!
JSON:
{
"result":[
{
"commonname":"Tamaraw",
"subresult":[
{
"latitude":"13.088847376649245",
"longitude":"121.0535496566772",
"province":"Mindoro"
},
{
"latitude":"14.898346071682198",
"longitude":"121.42616213302608",
"province":"General nakar"
},
{
"latitude":"14.44133541176629",
"longitude":"120.45936525802608",
"province":"Bataan"
}
]
},
{
"commonname":"Philippine Tarsier",
"subresult":[
{
"latitude":"9.810806171435631",
"longitude":"124.26143093023506",
"province":"Bohol"
}
]
},
{
"commonname":"Philippine Eagle",
"subresult":[
{
"latitude":"7.2396901503428",
"longitude":"125.44315069027664",
"province":"Davao City"
}
]
},
{
"commonname":"Visayan Warty Pig",
"subresult":[
{
"latitude":"9.651642644962154",
"longitude":"122.84131398239595",
"province":"Panay And Negros"
}
]
},
{
"commonname":"Philippine Fresh Water Crocodile",
"subresult":[
{
"latitude":"13.093068957060206",
"longitude":"121.06598892373722",
"province":"Mindoro"
}
]
},
{
"commonname":"Walden's Hornbill",
"subresult":[
{
"latitude":"10.071930427284427",
"longitude":"125.59779391691245",
"province":"Camiguin Sur and Dinagat Island"
},
{
"latitude":"14.656674396646768",
"longitude":"121.05812014083858",
"province":"Quezon"
}
]
},
{
"commonname":"Philippine Cockatoo",
"subresult":[
{
"latitude":"9.380944735295179",
"longitude":"118.38456063371927",
"province":"Palawan"
},
{
"latitude":"15.491670747921509",
"longitude":"120.94052188562534",
"province":"Cabanatuan City"
},
{
"latitude":"15.378556159943873",
"longitude":"121.39594973068233",
"province":"Dingalan"
}
]
},
{
"commonname":"Negros Bleeding-heart",
"subresult":[
{
"latitude":"9.551081019434731",
"longitude":"123.09185859510103",
"province":"Negros and Panay"
}
]
},
{
"commonname":"Philippine naked-backed fruit bat",
"subresult":[
{
"latitude":"9.646007526813666",
"longitude":"122.85255472090171",
"province":"Negros"
}
]
},
{
"commonname":"Philippine Forest Turtle",
"subresult":[
{
"latitude":"9.35368808473656",
"longitude":"118.36544272849846",
"province":"Palawan"
}
]
},
{
"commonname":"Dinagat bushy-tailed Cloud Rat",
"subresult":[
{
"latitude":"10.100726050965035",
"longitude":"125.59963979398412",
"province":"Dinagat Island"
}
]
},
{
"commonname":"Hawksbill Sea Turtle",
"subresult":[
{
"latitude":"6.984796116278719",
"longitude":"122.02642351890961",
"province":"Zamboanga"
}
]
},
{
"commonname":"Philippine Spotted Deer",
"subresult":[
{
"latitude":"16.229997551983594",
"longitude":"120.52623997214562",
"province":"Baguio"
}
]
}
]
}
Java code:
public JSONArray result;
public static final String JSON_ARRAY = "result";
public static final String TAG_COMMONNAME= "commonname";
public void getData(){
//Creating a string request
StringRequest stringRequests = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jo = null;
try {
//Parsing the fetched Json String to JSON Object
jo = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = jo.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getAnimals(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequests);
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

How to re-Order a JsonArray

I'm trying to re-order a JsonArray with putting a specif Column TransactionId to the first element of my Json Array :
Here Is my Json
`{
"ImportOperation":{
"Lines":{
"GoodsReceivalLine":[
{
"ExtWarehouseId":"Warehouse1",
"CustomData":{
"Item":[
{
"Key":{
"string":"Type"
},
"Value":{
"string":"Move"
}
}
]
},
"CustomAllocationData":{
"Item":[
{
"Key":{
"string":"Grade"
},
"Value":{
"string":"002"
}
}
]
}
},
{
"ExtWarehouseId":"Warehouse2",
"CustomData":{
"Item":[
{
"Key":{
"string":"Type"
},
"Value":{
"string":"Move"
}
}
]
},
"CustomAllocationData":{
"Item":[
{
"Key":{
"string":"Grade"
},
"Value":{
"string":"002"
}
}
]
}
}
]
}
}
}`
Now , i tried to add in GoodsReceivalLine array a random UUID TransactionId as a first elemet of my JSON array So that my Json would be :
`{
"ImportOperation":{
"Lines":{
"GoodsReceivalLine":[
{
"TransactionId":"RAndom UUID VAlue",
"ExtWarehouseId":"Warehouse1",
"CustomData":{
"Item":[
{
"Key":{
"string":"Type"
},
"Value":{
"string":"Move"
}
}
]
},
"CustomAllocationData":{
"Item":[
{
"Key":{
"string":"Grade"
},
"Value":{
"string":"002"
}
}
]
}
},
{
"TransactionId":"RAndom UUID VAlue",
"ExtWarehouseId":"Warehouse2",
"CustomData":{
"Item":[
{
"Key":{
"string":"Type"
},
"Value":{
"string":"Move"
}
}
]
},
"CustomAllocationData":{
"Item":[
{
"Key":{
"string":"Grade"
},
"Value":{
"string":"002"
}
}
]
}
}
]
}
}
}
`
For this i tried this code that works and generates my TransactionId properly but get the order of my Json as not expectedand very random order :
`JSONObject inputJo = new JSONObject((String)globalMap.get("row1.body"));
JSONObject impOpJo = inputJo.getJSONObject("ImportOperation");
JSONObject linesJo = impOpJo.getJSONObject("Lines");
JSONArray goodsRecJa = linesJo.getJSONArray("GoodsReceivalLine");
for(int i = 0; i<goodsRecJa.length(); i++){
JSONObject tmpObj = goodsRecJa.getJSONObject(i);
tmpObj.put("TransactionId", java.util.UUID.randomUUID().toString()) ;
}
System.out.println("*** Body : "+inputJo.toString()); `
Where i'm i mistaking and how could i correct that , is my loop not correct ? please i'm stack with that

Array inside an array - Java Codes

I am new at programming. I have this problem of fetching the values from sub array entitled "subresult". I have code of getting values from an array but it seems that it only gets the outer array and disregard the inner array. It is sad that I have no luck in this. Please respect my question because I'm just a beginner. Hoping an answer from you guys. Thank you!
JSON:
{
"result":[
{
"commonname":"Tamaraw",
"subresult":[
{
"latitude":"13.088847376649245",
"longitude":"121.0535496566772",
"province":"Mindoro"
},
{
"latitude":"14.898346071682198",
"longitude":"121.42616213302608",
"province":"General nakar"
},
{
"latitude":"14.44133541176629",
"longitude":"120.45936525802608",
"province":"Bataan"
}
]
},
{
"commonname":"Philippine Tarsier",
"subresult":[
{
"latitude":"9.810806171435631",
"longitude":"124.26143093023506",
"province":"Bohol"
}
]
},
{
"commonname":"Philippine Eagle",
"subresult":[
{
"latitude":"7.2396901503428",
"longitude":"125.44315069027664",
"province":"Davao City"
}
]
},
{
"commonname":"Visayan Warty Pig",
"subresult":[
{
"latitude":"9.651642644962154",
"longitude":"122.84131398239595",
"province":"Panay And Negros"
}
]
},
{
"commonname":"Philippine Fresh Water Crocodile",
"subresult":[
{
"latitude":"13.093068957060206",
"longitude":"121.06598892373722",
"province":"Mindoro"
}
]
},
{
"commonname":"Walden's Hornbill",
"subresult":[
{
"latitude":"10.071930427284427",
"longitude":"125.59779391691245",
"province":"Camiguin Sur and Dinagat Island"
},
{
"latitude":"14.656674396646768",
"longitude":"121.05812014083858",
"province":"Quezon"
}
]
},
{
"commonname":"Philippine Cockatoo",
"subresult":[
{
"latitude":"9.380944735295179",
"longitude":"118.38456063371927",
"province":"Palawan"
},
{
"latitude":"15.491670747921509",
"longitude":"120.94052188562534",
"province":"Cabanatuan City"
},
{
"latitude":"15.378556159943873",
"longitude":"121.39594973068233",
"province":"Dingalan"
}
]
},
{
"commonname":"Negros Bleeding-heart",
"subresult":[
{
"latitude":"9.551081019434731",
"longitude":"123.09185859510103",
"province":"Negros and Panay"
}
]
},
{
"commonname":"Philippine naked-backed fruit bat",
"subresult":[
{
"latitude":"9.646007526813666",
"longitude":"122.85255472090171",
"province":"Negros"
}
]
},
{
"commonname":"Philippine Forest Turtle",
"subresult":[
{
"latitude":"9.35368808473656",
"longitude":"118.36544272849846",
"province":"Palawan"
}
]
},
{
"commonname":"Dinagat bushy-tailed Cloud Rat",
"subresult":[
{
"latitude":"10.100726050965035",
"longitude":"125.59963979398412",
"province":"Dinagat Island"
}
]
},
{
"commonname":"Hawksbill Sea Turtle",
"subresult":[
{
"latitude":"6.984796116278719",
"longitude":"122.02642351890961",
"province":"Zamboanga"
}
]
},
{
"commonname":"Philippine Spotted Deer",
"subresult":[
{
"latitude":"16.229997551983594",
"longitude":"120.52623997214562",
"province":"Baguio"
}
]
}
]
}
Java code:
public JSONArray result;
public static final String JSON_ARRAY = "result";
public static final String TAG_COMMONNAME= "commonname";
public void getData(){
//Creating a string request
StringRequest stringRequests = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jo = null;
try {
//Parsing the fetched Json String to JSON Object
jo = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = jo.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getAnimals(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequests);
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getAnimals(JSONArray ja){
//Traversing through all the items in the json array
for(int i=0;i<ja.length();i++){
try {
//Getting json object
json = ja.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(TAG_COMMONNAME));
//TRY THIS
JsonArray subResultJsonArray = json.optJSONArray("subresult");
} catch (JSONException e) {
e.printStackTrace();
}
}

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}

I have json objects inside a json array but a long try i did not found a good result [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I want to parse and get them store in a arraylist to show in a spinner with single text as a company location in android.I am a fresher in android and don't know how
I have this json file coming from a url:
{
GetCompanyLocationResult:
{
LoginMessage:
{
ErrorMsg: null,
Success: true
},
UserLocation: [
{
Comp_Location: "ABCD-ABCD"
},
{
Comp_Location: "CBS-DELHI"
},
{
Comp_Location: "CBS-JAIPUR"
},
{
Comp_Location: "CBS-MEERUT"
},
{
Comp_Location: "CBS-NOIDA"
},
{
Comp_Location: "CBS-RAJASTHAN"
},
{
Comp_Location: "MISAP-DELHI"
},
{
Comp_Location: "MISAP-NOIDA"
},
{
Comp_Location: "SYNERGY-DELHI"
}
]
}
}
your json is not valid json please check your json here
valid JSON like below :
{
"GetCompanyLocationResult": {
"LoginMessage": {
"ErrorMsg": null,
"Success": true
},
"UserLocation": [{
"Comp_Location": "ABCD-ABCD"
},
{
"Comp_Location": "CBS-DELHI"
},
{
"Comp_Location": "CBS-JAIPUR"
},
{
"Comp_Location": "CBS-MEERUT"
},
{
"Comp_Location": "CBS-NOIDA"
},
{
"Comp_Location": "CBS-RAJASTHAN"
},
{
"Comp_Location": "MISAP-DELHI"
},
{
"Comp_Location": "MISAP-NOIDA"
},
{
"Comp_Location": "SYNERGY-DELHI"
}
]
}
}
key name should be in "" mark.
EX--> "GetCompanyLocationResult":{} Instead Of GetCompanyLocationResult:{}
Try this..it will save userLocations in ArrayList
ArrayList<String> arrayList = new ArrayList<>();
JSONObject obj = null;
try {
obj = new JSONObject(jsonString);
JSONObject obj1 = obj.getJSONObject("GetCompanyLocationResult");
JSONArray jArray = obj1.getJSONArray("UserLocation");
for (int i = 0; i <= jArray.length(); i++) {
arrayList.add(jArray.getJSONObject(i).getString("Comp_Location"));
System.out.println(arrayList.get(i).toString() + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
#Om Prakash try the below code:
private void test(JSONObject jsonObject) {
ArrayList<String> companyNameArray = new ArrayList<>();
if (jsonObject.has("GetCompanyLocationResult")) {
try {
JSONObject comapnyLocationObject = jsonObject.getJSONObject("GetCompanyLocationResult");
if (comapnyLocationObject.has("UserLocation")) {
Object obj = comapnyLocationObject.get("UserLocation");
if (obj instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) obj;
for (int index = 0; index < jsonArray.length(); index++) {
try {
JSONObject jsonComapny = jsonArray.getJSONObject(index);
if (jsonComapny.has("Comp_Location")) {
companyNameArray.add(jsonComapny.getString("Comp_Location"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Parsing json object in java, object not found

I'm trying to parse the following (expected) json response to return an array of id
{
"establishments":[
{
"establishment":{
"id":21,
"name":"Quick Bites"
}
},
{
"establishment":{
"id":16,
"name":"Casual Dining"
}
},
{
"establishment":{
"id":7,
"name":"Bar"
}
},
{
"establishment":{
"id":6,
"name":"Pub"
}
},
{
"establishment":{
"id":5,
"name":"Lounge"
}
},
{
"establishment":{
"id":31,
"name":"Bakery"
}
},
{
"establishment":{
"id":18,
"name":"Fine Dining"
}
},
{
"establishment":{
"id":275,
"name":"Pizzeria"
}
},
{
"establishment":{
"id":1,
"name":"Caf\u00e9"
}
},
{
"establishment":{
"id":24,
"name":"Deli"
}
},
{
"establishment":{
"id":285,
"name":"Fast Casual"
}
},
{
"establishment":{
"id":271,
"name":"Sandwich Shop"
}
},
{
"establishment":{
"id":282,
"name":"Taqueria"
}
},
{
"establishment":{
"id":283,
"name":"Brewery"
}
},
{
"establishment":{
"id":161,
"name":"Microbrewery"
}
},
{
"establishment":{
"id":23,
"name":"Dessert Parlour"
}
},
{
"establishment":{
"id":101,
"name":"Diner"
}
},
{
"establishment":{
"id":286,
"name":"Coffee Shop"
}
},
{
"establishment":{
"id":81,
"name":"Food Truck"
}
},
{
"establishment":{
"id":91,
"name":"Bistro"
}
},
{
"establishment":{
"id":272,
"name":"Cocktail Bar"
}
},
{
"establishment":{
"id":284,
"name":"Juice Bar"
}
},
{
"establishment":{
"id":281,
"name":"Fast Food"
}
},
{
"establishment":{
"id":8,
"name":"Club"
}
},
{
"establishment":{
"id":20,
"name":"Food Court"
}
},
{
"establishment":{
"id":278,
"name":"Wine Bar"
}
}
]
}
I'm using the following code:
private static void parseEstablishments (JSONObject r) {
System.out.println("in parseEstablishments");
System.out.println(r.length());
JSONArray array = r.getJSONArray("establishment");
List<String> list = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i).getString("id"));
}
System.out.println("done");
}
r.length prints out 1 and r.toString prints out {"encoding":"UTF8"}. I'm also getting the following error: JSONObject["establishment"] not found.
Not really sure what's wrong. Can anyone help? Thanks.
You can't access establishment if you didn't go into establishments. For example we have class A which has field with class B. You can't access B until you get A. Another example: When you eat orange you first eat what's inside or remove the skin?
You might also consider checking is your JSON what you expect it to be.
Hope this code snippet helps you..!!
private static void parseEstablishments (JSONObject r) throws JSONException {
System.out.println("in parseEstablishments");
System.out.println(r.length());
JSONArray array = r.getJSONArray("establishments");
List<String> list = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
JSONObject establishmentObj=new JSONObject(array.get(i).toString());
list.add(String.valueOf(new JSONObject(establishmentObj.get("establishment").toString()).get("id")));
}
System.out.println("List Of Ids:"+list);
System.out.println("done");
}
First of all , it should be
JSONArray array = r.getJSONArray("establishments");
The JSON array key is establishments with the s
Then because your object is nested in another object :
{
"establishment":{
"id":21,
"name":"Quick Bites"
}
}
Your loop needs to change :
for (int i = 0; i < array.length(); i++) {
JSONObject establishmentObj=array.getJSONObject(i)
.getJSONObject("establishment");
list.add(establishmentObj.getString("id"));
}

Categories

Resources