Im getting problems with parsing Json.
my json response.
{
"Persons": [
{
"id": 0,
"name": "William",
"image": "http://www.images-image2312321356.jpg",
"colors": [
"White",
"Red",
"Green"
]
},
{...}
Im trying this. but it causes a compile error
public void onResponse(JSONObject responseObject) {
try {
JSONArray rs = responseObject.getJSONArray("Persons");
for (int i = 0; i < rs.length(); i++) {
try {
final JSONObject c = rs.getJSONObject(i);
String name = c.getString("name");
items.add(name);
));
}
} catch (JSONException e) {
e.printStackTrace();
}
Any idea? Im using volley
public void onResponse(JSONObject responseObject) {
JSONArray rs = responseObject.getJSONArray("Persons");
if (rs != null || rs.length() > 0) {
for (int i = 0; i < rs.length(); i++) {
JSONObject obj = rs.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
String img = obj.getString("image");
JSONArray colors = obj.getJSONArray("colors");
for (int ii = 0; ii < colors.length(); ii++) {
String color = colors.getString(ii);
colors.add(color);
}
}
}
}
Related
I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId
I am working on an android application and somewhere in my application, I want to remove some JsonObject from jsonArray. Below is the JsonArray:
[
{
"id": 2,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/e0/39/01/137a8_8640.png?c=279d",
},
{
"id": 4,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/5f/3a/01/13826_c4c9.png?c=ff74",
},
{
"id": 1,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/ac/39/01/13774_7183.png?c=35ee",
},
{
"id": 5,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/a7/3a/01/1386e_d5c5.png?c=3f1e",
},
{
"id": 3,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/1d/3a/01/137e4_e803.png?c=9ab9",
},
{
"id": 6,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/cf/3a/01/13896_edab.png?c=1e7b",
}
]
Now from this JsonArray, I want to remove JsonObject which is having id equals to 2.
How can I do this, I want to optimize this code because, I can do it using a for loop, but I do not want to do it using for loop.
Is there any other way to do it. Please help me if anyone know about this.
Thanks a lot in advanced.
Assuming that you are using JsonArray from Gson library, you can use remove() method.
For example:
int idToRemove = 3;
JsonElement elementToRemove = null;
for(JsonElement e : jsonArray) {
JsonObject o = e.getAsJsonObject();
if(o.get("id").getAsInt() == idToRemove) {
elementToRemove = e;
break;
}
}
if (elementToRemove != null) jsonArray.remove(elementToRemove);
Alternatively, use Iterator<JsonElement> explicitly.
JSONArray jsonArray = new JSONArray(string);
int len = jsonArray.length();
int position = -1;
int wantedID = 2;
for (int i=0;i<len;i++){
JSONObject jsonObj = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObj.get("id"));
if (id == wantedID) {
position = i;
break;
}
}
JSONArray jsonArray_out = jsonArray;
if (position >= 0) {
//for 19 API use this: jsonArray_out.remove(position);
//or remove using this code:
jsonArray_out = remove(position, jsonArray);
}
String out = jsonArray_out.toString();
Using this methods you can remove data from JSON:
https://stackoverflow.com/a/12526047/1979882
public static JSONArray remove(final int idx, final JSONArray from) {
final List<JSONObject> objs = asList(from);
objs.remove(idx);
final JSONArray ja = new JSONArray();
for (final JSONObject obj : objs) {
ja.put(obj);
}
return ja;
}
public static List<JSONObject> asList(final JSONArray ja) {
final int len = ja.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = ja.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
or this:
https://stackoverflow.com/a/20250881/1979882
I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}
I've usually use Retrofit to do all parsing "dirty" work, but recently I've decided to parse json "by the hands". And I can't figure out how to parse nested arrays in array, there is my json:
[
{
"title":"Phone",
"subs":[
{
"id":157291,
"title":"Cell Phone Service"
},
{
"id":524624,
"title":"Landline Phone Service"
},
{
"id":157298,
"title":"Voice Over IP"
}
]
},
{
"title":"TV and Internet",
"subs":[
{
"id":157292,
"title":"Hardwire Internet"
},
{
"id":178472,
"title":"Television"
},
{
"id":524625,
"title":"Wireless Internet"
}
]
},
{
"title":"Entertainment",
"subs":[
{
"id":522695,
"title":"Music and Movies"
}
]
},
{
"title":"Bill Payment",
"subs":[
{
"id":179845,
"title":"Home Utilities"
}
]
},
{
"title":"Games and Social",
"subs":[
{
"id":157297,
"title":"Games",
"subs":[
{
"id":525000,
"title":"Category:Casual"
},
{
"id":525001,
"title":"Category:Online Games"
},
{
"id":525002,
"title":"Category:Action and Shooter Games"
},
{
"id":525003,
"title":"Category:RPG"
},
{
"id":525005,
"title":"Category:Strategy"
},
{
"id":525006,
"title":"Category:Adventure"
},
{
"id":525008,
"title":"Category:Simulators"
},
{
"id":525171,
"title":"Category:Portals and Services"
},
{
"id":525265,
"title":"Category:Game artefacts"
}
]
},
{
"id":524626,
"title":"Social Networks"
},
{
"id":522901,
"title":"Dating"
}
]
},
{
"title":"Finances",
"subs":[
{
"id":522747,
"title":"Loan Repayment"
}
]
},
{
"title":"Everyday Purchases",
"subs":[
{
"id":288993,
"title":"Beauty, Health, and Sports"
}
]
},
{
"title":"Travel",
"subs":[
{
"id":523297,
"title":"Travel Reservations"
},
{
"id":524634,
"title":"Travel Agencies"
}
]
},
{
"title":"Websites",
"subs":[
{
"id":160550,
"title":"Advertising"
},
{
"id":233554,
"title":"Domain Hosting"
}
]
},
{
"title":"And also:",
"subs":[
{
"id":179843,
"title":"Charity"
},
{
"id":524635,
"title":"Online auctions"
},
{
"id":522887,
"title":"Miscellaneous"
}
]
}
]
I've got the second-level nested array, using this piece of code, but how can I get the third-level array?
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And, by the way, how should I store this data in the database - I'm using Realm and I've created Category and SubCategory models, do I need to create another subcategory model for saving data from the third-level array?
Categoty model:
public class Category extends RealmObject {
#PrimaryKey
private String title;
private SubCategory subCategory;
//Getters and setters
}
And SubCategory model:
public class SubCategory extends RealmObject {
#PrimaryKey
private int id;
private String title;
//Getters and setters
}
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
Category c=new Category();
JSONObject jsonObject = jsonArray.getJSONObject(i);
c.setTitle(jsonObject.getString("title"));
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
SubCategory s=new SubCategory();
JSONObject nestedObject= nestedArray.getJSONObject(i);
s.setId(nestedObject.getString("id"));
s.setTitle(nestedObject.getString("title"));
}
c.setSubCategory(s);
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
JSONObject nestObj = nestedArray.getJSONObject(j);
if(nestObj.has("subs"))
{
JSONArray insideArray = nestObj.getJSONArray("subs");
for (int k = 0; k < insideArray .length(); k++) {
}
}
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
I want to get only some selected values from the JSON response.For example if JSON contains 100 string values then i need to take the values which are starting with # symbol from that 100 values.
How can I do that ?
Following is my JSON,
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
}]
Here I need to fetch Name which having # symbol
You can use below method to get the Name which start with # :
JSONObject jsonObject = new JSONObject(response);// u can change it as per your need
JSONArray jArray = jsonObject.getJSONArray("Obj");// if your `Obj` is an JsonArray
for (int i = 0; i < jArray.length(); i++) {
String json_name = jArray.getJSONObject(i).getString("NAME");
if(json_name.startsWith("#"))
{
Log.d(TAG,"It start with #");
}
}
Try out as below:
private void parseJSON(String json) {
try {
JSONArray items = new JSONArray(<your Json Response>);
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
System.err.println("Object---" + item.getString("Obj"));
JSONObject obj=item.getJSONObject("Obj");
for (int j = 0; j < obj.length(); j++) {
String Name=obj.getString("NAME");
if(obj.getString("NAME").toString().contains("#"))
{
Log.d("Name starts with-->", Name);
}
else
{
Log.d("Name does not start with-->", Name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this.
first of all that's not a valid json may be below json is correct format
[
{
"Obj": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
}
]
}
]
if your response like above try below code this may help you.
try {
JSONArray jsoArray = new JSONArray(json);
JSONArray JobjArray = jsoArray.getJSONObject(0).getJSONArray("Obj");
for(int i=0; i < JobjArray.length(); i++)
{
JSONObject Jobj = JobjArray.getJSONObject(i);
Iterator<String> iter = Jobj.keys();
while (iter.hasNext()) {
String key = iter.next();
Log.v("key--", key);
try {
Object value = Jobj.get(key);
Log.v("value--", ""+value);
String str_value = value.toString().trim();
if(str_value.startsWith("#"))
{
Log.d(""+str_value,"value started with #");
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}