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();
}
}
Related
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
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();
}
}
This is the example of ArrayList that i need to fetch, how to fetch this Arrays? Im using GET method of volley to fetch this Array and show in Recycler View.
[
{
"_id": "a2a1",
"name": "Flower",
"image": {
"_id": "a2a2",
"name": "flower.jpg",
"url": "/uploads/c8c8c.jpg",
"related": [
"a2a1"
],
"id": "0a2a2"
},
},
{
"_id": "433d",
"name": "Bouquet",
"id": "433d",
"image": {
"_id": "433e",
"name": "baloon.jpg",
"url": "/uploads/247db.jpg",
"related": [
"433d"
],
"id": "433e"
},
}]
This is my code by using Get method of Volley to fetch the array, i already put the correct api but i didnt get the list of the array.
private void FlowerList(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
FlowerModel[] models = gson.fromJson(String.valueOf(json.getJSONArray(null)), FlowerModel[].class);
flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
if you are using Gson verson 2.8' then
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, TypeToken.getParameterized(ArrayList.class, FlowerModel.class).getType());
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
for older version
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, new TypeToken<ArrayList<FlowerModel>>(){}.getType(););
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
try this....i have modified your code
ArrayList<String> stringArrayList;
String id1,name,id2;
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
JSONArray jsonArray=json.getJSONArray("Your_response_arrayName");
stringArrayList=new ArrayList<>();
for(i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArrayList.add(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
hope this will help you
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();
}
}
}
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"));
}