Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
if need them as JSONArray the you can try
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
in case keys like test1,test2,test3...
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
you can get your JSONArray this way.
Related
In my Android app, I am fetching the details of Points table of a tournament to convert the output to a string from JSON object to Java
JSON object is shown below:
{
"group": {
"Teams": [
{
"name": "Team 1",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 2",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 3",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 4",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 5",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 6",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 7",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
},
{
"name": "Team 8",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
}
]
}
}
Android Java Code is below:
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJSONObject("Teams");
if (teams.has("0")) {
JSONObject teams_object = teams.getJSONObject("0");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
But I am getting the error where I print the error message through getMessage() method. Here is the error below:
Error: Value ["name","p","w","l","points"] at header of type org.json.JSONArray cannot be converted to JSONObject
Can anyone please help like where I am going wrong or what is the fix ? Thanks in advance
In your Json Teams holds the Array of Object and you are parsing wrong.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONObject groups = jsonObject.getJSONObject("group");
JSONArray teams = groups.getJSONArray("Teams");
for(int i=0;i<teams.length();i++){
JSONObject obj = teams.getJSONObject(i);
name.append(obj.getString("name")+"\n");
}
There is 4 mistakes in your code,
1.You have to check whether group has teams instead match has teams.
2.You have to get team as JSONArray instead of JSONObject because it is array.
3.You have to check the size of team, instead of find the object with key 0, there is no object with name 0 in your group,
4.You have to get the object based on index instead of key(ie., 0)
Please check the working code, this is tested
try {
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
if (teams.length() > 0) {
JSONObject teams_object =(JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
Log.v(TAG, team_name);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject subObject = jsonObject.getJSONObject("group") ;
JSONArray jsonArray = subObject.getJSONArray("Teams");
for (int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String p= jsonObject.getString("p");
String w= jsonObject.getString("w");
String l= jsonObject.getString("l");
String points = jsonObject.getString("points");
}
} catch (Exception e) {
e.printStackTrace();
}
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
// for only 0th element use below code else looping
JSONObject teams_object = (JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
Error: Value ["name","p","w","l","points"] at header of type
org.json.JSONArray cannot be converted to JSONObject
You are getting the error because there is an Array of Teams and you are trying parse with JSONObject
Please check below code snippet. It will work.
try {
JSONObject match = new JSONObject("your_response");
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
for(int i=0; i < teams.length(); i++){
JSONObject teams_object = (JSONObject) teams.get(i);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this #SaAsh, I have just edited by taking your answer
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJsonArray("Teams");
for(int i = 0 ; i < teams.length();i++){
JSONObject teams_object = teams.getJSONObject("i");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
}
I have two items in arraylist
Position 0 : product_id=500,amout=1
Position 1 : product_id=501,amout=1
I want to create this type of json
{
"user_id": "3",
"shipping_id": "1",
"payment_id": "2",
"products": {
"500": {
"product_id": "500",
"amount": "1"
},
"501": {
"product_id": "501",
"amount":"1"
}
}
}
This is my code
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
jsonObject.accumulate("products", productObject);
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
productObject.accumulate(b, numberObject);
}
I am getting this Responce:
{
"user_id":"230",
"shipping_id":"1",
"payment_id":"14",
"products":[
{"579":
{
"product_id":"579",
"amount":"1"
}
},
{"593":
{
"product_id":"593",
"amount":"1"
}
}]
}
But I want this json Responce please help for getting resultant responce.
{
"user_id": "3",
"shipping_id": "1",
"payment_id": "2",
"products": {
"500": {
"product_id": "500",
"amount": "1"
},
"501": {
"product_id": "501",
"amount":"1"
}
}
}
You can use the following code to generate your JSON,
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_id", usr);
jsonObject.put("shipping_id", shipping_id);
jsonObject.put("payment_id", payment_id);
JSONObject productValueObject = new JSONObject();
for (int i = 0; i < alProductss.size(); i++) {
String a = alProductss.get(i).getAmount();
String b = alProductss.get(i).getProduct_id();
JSONObject projectObj = new JSONObject();
projectObj.put("product_id", b);
projectObj.put("amount", a);
productValueObject.put(b, projectObj);
}
jsonObject.put("products", productValueObject);
} catch (JSONException e) {
e.printStackTrace();
}
try this one..
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
JSONArray jsonArray = new JSONArray();
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
jsonArray.put(numberObject);
}
jsonObject.put("products",jsonArray);
I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");
[
{
"countries": [
{
"id": 1,
"country": "India"
},
{
"id": 2,
"country": "Australia"
},
{
"id": 3,
"country": "Srilanka"
},
{
"id": 4,
"country": "Pakistan"
},
{
"id": 5,
"country": "Switzerland"
}
]
}
]
How to parse this Json Response in Android. i am not getting any proper solution.
please help me.
Do it like this...
JSONArray arr = locs.getJSONArray("countries");
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String con = rec.getString("country");
// ...
}
JSONArray jArr=new JSONArray(response);
for(int i=0;i<jArr.length;i++)
{
id[]=jArr.getJSONObject(i).getInt("id");
con[]=jArr.getJSONObject(i).getString("country");
}
http://developer.android.com/reference/org/json/JSONTokener.html
I've also seen Jackson used in Android apps.
JSONArray countriesobj = new JSONArray();
JSONObject json;
try {
JSONObject jObject = new JSONObject(response);
json = jObject;
countriesobj = json.getJSONArray("countries");
country = new String[countriesobj.length()];
for (int i = 0; i < countriesobj.length(); i++) {
JSONObject e = countriesobj.getJSONObject(i);
country[i] = e.getString("country");
}
} catch (Exception e) {
e.printStackTrace();
}
i want to parse the json object using json library.
{
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
}
}
Using JSON..
JSONObject object = new JSONObject(yourString);
JSONObject batters = object.getJSONObject("batters");
JSONArray batter = batters.getJSONArray("batter");
for(int i = 0 ; i < batter.length() ; i++) {
JSONObject object1 = (JSONObject) batter.get(i);
String id = object1.getString("id");
}
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}