I need to get data from house array, My json file looks like,
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
I just tried like this to parse data from json,
InputStream inputStream = getResources().openRawResource(R.raw.house_details);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
house_ID = jArray.getJSONObject(i).getString("houseID");
is_painted = jArray.getJSONObject(i).getBoolean("isPainted");
owner_gender = jArray.getJSONObject(i).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
} catch (Exception e) {
e.printStackTrace();
}
But I couldn't get what I am expecting, Please help me get all data from json.
You can use Gson lib to get the data from Json easy way and your structure will be like this
public class Response{
#SerializedName("mydata")
private Mydata mydata;
public void setMydata(Mydata mydata){
this.mydata = mydata;
}
public Mydata getMydata(){
return mydata;
}
#Override
public String toString(){
return
"Response{" +
"mydata = '" + mydata + '\'' +
"}";
}
}
public class Mydata{
#SerializedName("totalRoads")
private String totalRoads;
#SerializedName("noOfHouse")
private String noOfHouse;
#SerializedName("house")
private List<HouseItem> house;
public void setTotalRoads(String totalRoads){
this.totalRoads = totalRoads;
}
public String getTotalRoads(){
return totalRoads;
}
public void setNoOfHouse(String noOfHouse){
this.noOfHouse = noOfHouse;
}
public String getNoOfHouse(){
return noOfHouse;
}
public void setHouse(List<HouseItem> house){
this.house = house;
}
public List<HouseItem> getHouse(){
return house;
}
#Override
public String toString(){
return
"Mydata{" +
"totalRoads = '" + totalRoads + '\'' +
",noOfHouse = '" + noOfHouse + '\'' +
",house = '" + house + '\'' +
"}";
}
}
public class HouseItem{
#SerializedName("road")
private String road;
#SerializedName("left")
private List<LeftItem> left;
#SerializedName("right")
private List<RightItem> right;
public void setRoad(String road){
this.road = road;
}
public String getRoad(){
return road;
}
public void setLeft(List<LeftItem> left){
this.left = left;
}
public List<LeftItem> getLeft(){
return left;
}
public void setRight(List<RightItem> right){
this.right = right;
}
public List<RightItem> getRight(){
return right;
}
#Override
public String toString(){
return
"HouseItem{" +
"road = '" + road + '\'' +
",left = '" + left + '\'' +
",right = '" + right + '\'' +
"}";
}
}
Hi your json is not valid one
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj= jArray.getJSONObject(i);
JSONArray right = obj.getJSONArray("right");
JSONArray left= obj.getJSONArray("left");
for(int j=0;j<right.length();j++)
{
house_ID = right.getJSONObject(j).getString("houseID");
is_painted = right.getJSONObject(j).getBoolean("isPainted");
owner_gender = right.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
for(int j=0;j<left.length();j++)
{
house_ID = left.getJSONObject(j).getString("houseID");
is_painted = left.getJSONObject(j).getBoolean("isPainted");
owner_gender = left.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
}
} catch (Exception e) {
e.printStackTrace();
}
1- Create a model for houseData i.e.
public class HotelEntity {
private String houseID;
private String isPainted;
private String ownerGender;
// add getter and setter here
}
2- Parse data from right and left from each house object
for (int i = 0; i < jArray.length(); i++) {
//get the data and map it object
Array.getJSONObject(i).getString("right");
for {
// add all models to list
}
Array.getJSONObject(i).getString("left");
for {
// add all models to list
}
}
3 Add it in ArrayList of your houseEntity.
Also, you can use Gson for the json to object conversion.
You don't have to manually parse data from json.
You can create object from your json String with
http://www.jsonschema2pojo.org/
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("mydata")
#Expose
private Mydata mydata;
public Mydata getMydata() {
return mydata;
}
public void setMydata(Mydata mydata) {
this.mydata = mydata;
}
}
-----------------------------------com.example.House.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class House {
#SerializedName("road")
#Expose
private String road;
#SerializedName("right")
#Expose
private List<Right> right = null;
#SerializedName("left")
#Expose
private List<Left> left = null;
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
public List<Right> getRight() {
return right;
}
public void setRight(List<Right> right) {
this.right = right;
}
public List<Left> getLeft() {
return left;
}
public void setLeft(List<Left> left) {
this.left = left;
}
}
-----------------------------------com.example.Left.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Left {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
-----------------------------------com.example.Mydata.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mydata {
#SerializedName("totalRoads")
#Expose
private String totalRoads;
#SerializedName("noOfHouse")
#Expose
private String noOfHouse;
#SerializedName("house")
#Expose
private List<House> house = null;
public String getTotalRoads() {
return totalRoads;
}
public void setTotalRoads(String totalRoads) {
this.totalRoads = totalRoads;
}
public String getNoOfHouse() {
return noOfHouse;
}
public void setNoOfHouse(String noOfHouse) {
this.noOfHouse = noOfHouse;
}
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}
}
-----------------------------------com.example.Right.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Right {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
And you can get everything with:
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
Gson g = new Gson();
Example example = g.fromJson(jObject .toString(), Example.class);
You can get value from Example.
Mydata mydata = example.getMyData();
List<House> lstHouse = mydata.getHouse();
for (i= 0; i < lstHouse.size(); i++){
House house = lstHouse.get(i);
String road = house.getRoad();
List<Right> lstRight = house.getRight();
for (j= 0; j < lstRight .size(); j++){
Right right = lstRight.get(j);
String houseID = right.getHouseID();
String isPainted = right.getIsPainted();
String ownerGender = right.getOwnerGender();
}
List<Left> lstLeft = house.getLeft();
for (k= 0; k < lstLeft .size(); k++){
Left left= lstLeft .get(k);
String houseID = left.getHouseID();
String isPainted = left.getIsPainted();
String ownerGender = left.getOwnerGender();
}
}
I hope it can help your problem!
You're trying to access data from house to houseId, but you have to go through right and left structures previously.
houseID is inside the right array not in house array.
Try this :
JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObj = jArray.getJSONObject(i);
JSONArray jsonArray = jsonObj.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
house_ID = jsonArray.getJSONObject(j).getString("houseID");
is_painted = jsonArray.getJSONObject(j).getBoolean("isPainted");
owner_gender = jsonArray.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
}
Here is a solution which is very close to your implementation, however, correct, and will also read the "left" array :)
InputStream inputStream = getResources().openRawResource(R.raw.sojson);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray houseArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < houseArray.length(); i++) {
JSONObject ob = houseArray.getJSONObject(i);
JSONArray rightArray = ob.getJSONArray("right");
for (int r = 0; r < rightArray.length(); r++) {
house_ID = rightArray.getJSONObject(r).getString("houseID");
is_painted = rightArray.getJSONObject(r).getBoolean("isPainted");
owner_gender = rightArray.getJSONObject(r).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
JSONArray leftArray = ob.getJSONArray("left");
for (int l = 0; l < leftArray.length(); l++) {
house_ID = leftArray.getJSONObject(l).getString("houseID");
is_painted = leftArray.getJSONObject(l).getBoolean("isPainted");
owner_gender = leftArray.getJSONObject(l).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
}
} catch (Exception e) {
e.printStackTrace();
}
Be sure to use valid JSON:
{
"mydata":{
"totalRoads":"13",
"noOfHouse":"5",
"house":[
{
"road":"1",
"right":[
{
"houseID":"A3",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A4",
"isPainted":"true",
"ownerGender":"female"
}
],
"left":[
{
"houseID":"A1",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A2",
"isPainted":"false",
"ownerGender":"female"
}
]
},
{
"road":"2",
"right":[
{
"houseID":"B3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"B4",
"isPainted":"true",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"B1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"B2",
"isPainted":"true",
"ownerGender":"male"
}
]
},
{
"road":"3",
"right":[
{
"houseID":"C3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"C4",
"isPainted":"false",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"C1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"C2",
"isPainted":"false",
"ownerGender":"male"
}
]
}
]
}
}
house_ID = jArray.getJSONObject(i).getString("houseID"); // WRONG WAY
I guess JSONException will occur.
You should create two FOR loop.
for (int i = 0; i < jArray.length(); i++)
{
JSONObject _jOBJ = jArray.getJSONObject(i);
JSONArray jsonArray = _jOBJ.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
JSONObject _jOBJCHILD = jsonArray.getJSONObject(j);
String str_HOUSEID = _jOBJCHILD.getString("houseID");
}
}
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONObject ja= new JSONObject(jsonData);
persons.clear();
Person s=null;
JSONObject jo=ja.getJSONObject("full_name");
if (jo.equals("John")) {
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
I'm going to guess that you have a JSONArray of person and you want to get the object that has person = John.
If the data is like this
[{
"full_name": "John Smith",
"sex": "male",
"location": "New York, NY, United States"
}, {
"full_name": "Angela Johnson",
"sex": "female",
"location": "San Diego, CA, United States"
}]
You can write:
JSONArray people = new JSONArray(jsondata);
int index = 0;
for (int i = 0; i < people.length(); i++) {
JSONObject tmpObj = people.getJSONObject(i);
string name = tmpObj.getString("full_name");
if (name == "John") {
index = i;
break;
}
}
JSONObject johnObjExample = people.getJSONObject(index);
string johnName = johnObjExample.getString("full_name");
int id = johnObjExample.getInt("id");
String name = johnObjExample.getString("full_name");
String sex = johnObjExample.getString("sex");
String location = johnObjExample.getString("location");
-- I know parsing, i have successfully parsed below data, but when web-service is upgraded i need to parse object inside object.
- I tried many example but getting error.
Code for Parsing :
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "Message";
private final String KEY_MSG1 = "Message";
// private final String KEY_AddressList = "addressList";
private final String KEY_USERINFO = "user_info";
ArrayList<HashMap<String, String>> arraylist;
private final String KEY_DATA = "data";
private final String KEY_USERDATA = "userdata";
public ArrayList<HashMap<String, String>> getList(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// JSONObject job = obj.getJSONObject("User");
Log.d("obj", obj.toString());
String user_id = obj.getString(Constants.Params.ID);
String createdate = obj.getStringAndyConstants.Params.CREATEDDATE);
String postImage = obj.getString(Constants.Params.IMAGE);
map.put(AndyConstants.Params.ID, user_id);
map.put(AndyConstants.Params.CREATEDDATE, createdate);
map.put(AndyConstants.Params.IMAGE, postImage);
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
for (int j = 0; j < jsonArrayUser.length(); j++) {
HashMap<String, String> mapUser = new HashMap<String, String>();
JSONObject businessObject = jsonArrayUser.getJSONObject(j);
Log.d("obj", businessObject.toString());
}
Log.d("map", map.toString());
arraylist.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return arraylist;
}
Error Log :
org.json.JSONException: No value for data
E/array: []
E/adapter: []
Json :
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}
You dont need this line
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
and change
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
to
JSONObject userData = obj.getJSONObject("userdata");
String firstName = userData.getString("first_name");
String lastName = userData.getString("last_name");
As you can see from the JSON
"data":
[{"user_id":"46",
"image":"",
"createdate":"2016-05-11 06:05:12",
"userdata":{"first_name
data is having the object [ which denotes an Array while userData shows a { which is a JSONObject
I notice that your JSON has some errors. is this the complete Json response?
Because JSON response should be something like this:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}]
}
You will notice that there is no close for [ after userdata in your Json.
i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.
I have a json file formatted like this (only the actual file has no whitespace):
{
"main": [
{
"sections": [
"sec1",
"sec2"
],
"title": "Section List 1"
},
{
"sections": [
"sec3",
"sec4",
"sec5"
],
"title": "Section List 2"
}
],
"sections": {
"sec1": {
"products": [
"prod1",
"prod2"
]
},
"sec2": {
"products": [
"prod3"
]
}
},
"products": {
"prod1": {
"url": "url1.gif",
"title": "Product 1"
},
"prod2": {
"url": "url2.gif",
"title": "Product 2"
},
"prod3": {
"url": "url3.gif",
"title": "Product 3"
}
}
}
When I attempt to send the data for that file into JSONObject, the JSONObject being loaded only contains the final object in the top list, in this case "products". Right now, my code to load the JSONObject is this:
JSONObject dlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
I've also tried storing the data in a String first and giving that to the JSONObject constructor, I've tried giving that String to a JSONTokener first, and giving that tokener to the JSONObject constructor. Both the String and the JSONTokener contain the entire file, but once it gets put into the JSONObject, it's always the same thing - "main" and "sections" get cut out, and only "products" remains.
Here's the rest of my relevant code:
public class MapsListFragment extends ListFragment
{
private static JSONObject mDlResult;
private ArrayAdapter<MapInfo> mMapListAdapter = null;
private class MapInfo
{
private String mText;
private String mURL;
MapInfo(String inText, String inURL)
{
mText = inText;
mURL = inURL;
}
public String URL()
{
return mURL;
}
#Override
public String toString()
{
return mText;
}
}
public class MapsListUpdater extends AsyncTask<String, String, JSONObject>
{
private static final String URL = "http://jsonURL/products.json";
private Date lastUpdate;
#Override
protected JSONObject doInBackground(String... inObjects)
{
Date ifModifiedSince = lastUpdate;
try
{
HttpURLConnection cnxn = (HttpURLConnection) new URL(URL).openConnection();
if (ifModifiedSince != null)
cnxn.setIfModifiedSince(ifModifiedSince.getTime());
cnxn.connect();
if (cnxn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED)
{
mDlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
}
cnxn.disconnect();
}
catch (Exception e)
{
boolean check = true;
}
return mDlResult;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
try
{
// This is really ugly and brute-forcey, but it's the only way I could get JSONObjects populated with ALL the data!
/*String[] tryThis = mDlResult.split(",\"sections\":");
tryThis[0] += '}';
tryThis[1] = tryThis[1].substring(0, tryThis[1].indexOf("]}},\"products\":"));
tryThis[1] = "{\"sections\":" + tryThis[1] + "]}}}";*/
JSONObject mainObj = mDlResult.getJSONObject("main");//new JSONObject(mDlResult);
JSONArray mainArray = mainObj.getJSONArray("main");
Vector<String> titles = new Vector<String>();
mMapListAdapter.clear();
for (int i = 0; i < mainArray.length(); i++)
{
JSONObject object = mainArray.getJSONObject(i);
String title = object.getString("title");
if(!titles.contains(title))
{
titles.add(title);
mMapListAdapter.add(new MapInfo(object.getString("title"), null));
}
}
}
catch (Exception e)
{
boolean check = true;
}
}
}
}
I feel a little foolish now. As it turns out, the JSONObject was getting EXACTLY what I asked it for... only the objects within it were getting reordered, so I couldn't see the first 2 objects in my debugger!
Try reading it into a JSONArray and let me know how you get on:
JSONArray dlResult = new JSONArray(cnxn.getInputStream());