(SOLVED) How to parse this json nested array [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
I got stuck in parsing this JSON, I has read a some references in GitHub or google and not same for this case, can anyone give me guided or references
{
"index":
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
}
EDIT: we has found a more simple json format
The solve by me
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
try {
JSONObject jsonArray = new JSONObject(response);
JSONArray list = jsonArray.getJSONArray("data");
for (int i = 0; i <list.length(); i++) {
String id= list.getJSONObject(i).getString("id");
String name = list.getJSONObject(i).getString("name");
String room= list.getJSONObject(i).getString("room");
KItem KTItem = new KasusItem(id,name,room);
kItemList.add(KTItem);
}

JSONArray data = JSONObject(response).getJSONObject("index).getJSONArray("data);
for(int i=0; i<data.length; i++){
JSONObject obj = data.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
}

Related

Extracting the value of attribute from a given string [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed last year.
I have a method named getPayDetails() which return type is a string
pay.getPaymentDetails() of which return type is a string and it returns the below string
[
{
"mcTtid":201657083281,
"cardLast4Digits":"0887",
"paymentType":"CREDIT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"CREDIT CARD"
}
},
{
"veTtid":21656148003,
"cardLast4Digits":"4777",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"GIFT CARD"
}
},
{
"mcTtid":201625819,
"cardLast4Digits":"8388",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"w",
"name":"GIFT CARD"
}
}
]
I need to extract the value of the attribute paymentType from the above string so the value of attribute paymentType in the above string is CREDIT CARD in a separate string variable. how can I do this?
I would recommend to use org.json library that is very easy.
After that something like this
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONArray arr = new JSONArray(jsonString);
for (int i = 0; i < arr.length(); i++)
{
String paymentType = arr.getJSONObject(i).getString("paymentType");
}

Parse 2d Json in java [duplicate]

This question already has answers here:
How to parse JSON 2D array using Java
(2 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Trying to parse this type of json format in java
{
"output": "success",
"result": [
{
"id": 1,
"label": "name",
},
{
"id": 2,
"label": "name_2",
}
]
}
I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result.
And this is i tried so far.
try {
JSONArray myJson = new JSONArray(response);
String status = myJson.getString(Integer.parseInt("output"));
if(status.equalsIgnoreCase("success")) {
for (int i = 0; i < myJson.length(); i++) {
JSONObject obj = myJson.getJSONObject(i);
name.add(obj.getString("label"));
}
Log.e("list" , name.toString());
}
} catch (Exception e) {
}
String responceStr = ...; // here is your full responce string
try {
JSONObject responce = new JSONObject(responceStr);
String status = responce.getString("output");
if ("success".equalsIgnoreCase(status)) {
JSONArray result = responce.getJSONArray("result");
for (int i=0; i < result.length(); i++){
JSONObject jsonPair = result.getJSONObject(i);
int id = jsonPair.getInt("id");
String label = jsonPair.getString("label");
}
}
} catch (JSONException e){
}
Integer.parseInt("123") -- is OK.
Integer.parseInt("output") -- is NOT OK.
because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.
The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result.
So change myJson to JSONObject and after checking the success field,
create a new variable
JSONArray resultArray = myJson.getArray("result");
and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add
e.printStackTrace();
in the catch block.

Fetch the key value from JSON String Android [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I want to display all data in Key value pair in a below JSON String.
response {
community: “worker”
communitystr: "<null>";
workspace: abs;
email: "<null>";
admin: false;
persona: "<null>";
userinfo: {
info: {
contact1: {
firstname: “jon”;
lastname: “Doe”
phone: “9885678905”;
objectname: contact;
id: 9;
};
event1: {
eventname: “party”;
description: "";
order: 6;
id: 4;
objectname: events;
};
files: {
filename: “sample”;
description: "";
order: 11;
id: 11;
objectname: files;
};
};
};
As I am new to this finding difficulty. how to get the key value in array or any other accessible format ? thanks for any help
First your json format is not correct, if you try to use JSONObject or GSON library is will throw not json type exception.
Please use a correct format of json something like this.
{
[
{
username: "somename",
userId : "1"
},
{
username: "somename2",
userId: "2"
}
]
}
General JSONObject contain JSONArray or JSONObject which you can parse it using android built in JSON.
JSONArray jsonArray = new JSONArray(yourJSONArray);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String username = json.getString("username"); //here is how to get username key
}
Here is how you loop through every key and value inside your JSON object
JSONArray array = new JSONObject(result);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = jsonObject.getString(key)
Log.d(TAG,"key = "+key+" value = "+value); // always use tag in log cat for preventing confusion
}
Regardless anything you still need to have a proper format of JSON.

How to store JSON response in an array list? [duplicate]

This question already has answers here:
Converting JSONarray to ArrayList
(23 answers)
Closed 8 years ago.
I want to store a JSON response in array list so that it will be easy to fetch data and assign it to other variables.
This is my JSON response:
{
"statusCode":"1001",
"message":"Success",
"response":{
"holidays":[
{
"holidayId":78,
"year":2015,
"date":"2015-01-01",
"day":"Thrusday",
"occasion":"New Year Day",
},
{
"holidayId":79,
"year":2015,
"date":"2015-01-15",
"day":"Thrusday",
"occasion":"Pongal/Sankranthi",
},
{
"holidayId":80,
"year":2015,
"date":"2015-01-26",
"day":"Monday",
"occasion":"Republic Day",
}
],
"year":0
}
}
This is the way I am fetching data from the response:
JSONObject jobj = new JSONObject(result);
String statusCode = jobj.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
System.out.println("SUCCESS!");
String response = jobj.getString("response");
JSONObject obj = new JSONObject(response);
String holidays = obj.getString("holidays");
ArrayList<HolidayResponse> holidayResponse = holidays; //This stmt. shows me error
}
How do I solve this issue? Please help me.
that is because of a JSON parse exception:
the holidays is a JSON array.Hence the correct way would be:
JSONObject obj = new JSONObject(response);
JSONArray holidays = obj.getJSONArray("holidays");
look here to convert that to array list.
Instead of all this hassle,you could use Gson or Jackson

How to convert JSON response to string in Android? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON Array iteration in Android/Java
I am developing an app where i am using the following JSONWeb Services Code. Everything is working good and getting response as JSON Array. I am not having any idea how to convert JSON Array to string. The response i am getting is in the following pattern..
Json Respone
[
{
"Id":101,
"Movie":"xxxxx",
"Available":
[
{
"date":"31-08-2012",
"timings":
[
"10:15",
"10:30",
"10:40"
]
},
{
"date":"1-09-2012",
"timings":
[
"10:15",
"10:30",
"10:40"
]
}
]
}
]
This is the response i am getting. Can anyone suggest me how to convert the following Json Response to string in android and i want to display that data in listview in android native.
Check the link
It shows the full example to communicate with the server and get response in Json format.
Though in this PHP,MySql is used but I guess the json response you get is same for all languages.
look at this sample and convert per your need
ps: a json array is one which starts with [ and ends with ]
a json object starts with{ and ends with } so in your case available is a json array and its 1 st object contains a json string date and another json array timings
JSONArray ja =jso.getJSONArray("Available");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj=ja.getJSONObject(i);
xyz[i]=jobj.getString("date");
abcd[i]=jobj.getJSONArray("timings").tostring;
}
}
edit:
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try { for (int i=0; i< json.length(); i++) {
JSONObject details = json.getJSONObject(i);
String id = details.getString("Id");
String name = details.getString("Name");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id); map.put(TAG_NAME, name);
contactList.add(map)
JSONArray ja=details.getJSONArray("Available");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj=ja.getJSONObject(i);
String a =jobj.getString("date");
String b =jobj.getJSONArray("timings").tostring;
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("a", a); map2.put("b", b);
contactList.add(map2)
}
}

Categories

Resources