error parsing Json with android - android

I have an error while trying to parse json. Can you help me please? I read the json url, but it gives me an exception when I'm trying to parse the json.
The code:
public String lecturaJsonTusPerlas() {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.tvnotas.com.mx/rss/feed/tvn-horoscopo.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
return result;
} catch (Exception e) {
Log.d("DEFEKAS","EXCEPCION");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
To read json:
JSONArray jsonArray2 = new JSONArray(lecturaJsonTusPerlas);
for (int i = 0; i < jsonArray2.length(); i++) {
JSONObject jsonObject = jsonArray2.getJSONObject(i);
String atr1 = null;
boolean var1 = jsonObject.getBoolean(atr1);
String atr2 = null;
int var2 = jsonObject.getInt(atr2);
String atr4 = null;
String var3 = jsonObject.getString(atr4);
}
I thing that the url is json because when I'm trying to extract with a google chrome extension I dont have any problem.

What you get is a JSONObject
JSONObject jb = new JSONObject(lecturaJsonTusPerlas());
Your json looks like below from the link you have used
{ // jsonobject node
"#attributes": {
"version": "2.0"
},
"channel": {
"title": "TV Notas",
"link": "http://www.tvnotas.com.mx",
"description": "TV Notas - Horoscopos",
"pubDate": "Mon, 23 Sep 2013 2:30:12 -0500",
"generator": "http://www.tvnotas.com.mx",
"language": "es",
"item": [ // json array of item's
{
"title": "Acuario",
"link": "http://usa.tvnotas.com.mx/horoscopo/1-acuario/",
"pubDate": "Mon, 23 Sep 2013 02:30:12 -0500",
"category": "Horoscopo",
"guid": "http://www.tvnotas.com.mx/horoscopo/1-acuario/",
"description": "Si has sido soberbio con tus compañeros de trabajo o empleados, con familiares o amigos y no les has perdonado sus malos momentos, ahora se te presentará la oportunidad de estrechar lazos.",
"enclosure": {
"#attributes": {
"url": "http://www.tvnotas.com.mx/advf/imagenes/2013/01/50fdbd604f653_150x118.jpg",
"length": "3587",
"type": "image/jpeg"
}
},
"elemento": "Aire",
"planeta": "Urano",
"signo_compatible": "Cáncer",
"signo_enemigo": "El excéntrico",
"numero": "25",
"arquetipo": "El Loco Sabio",
"arcangel": "Sakmakrel",
"color": "Verde",
"dia_suerte": "28"
},
....
To parse
try {
JSONObject jb = new JSONObject(lecturaJsonTusPerlas());
JSONObject job = jb.getJSONObject("channel");
String channeltitle= job.getString("title");
String channellink= job.getString("link");
String channeldecription= job.getString("description");
String channeldpubdate= job.getString("pubDate");
String channeldgenerator = job.getString("generator");
String channeldlanguage = job.getString("language");
JSONArray jr = job.getJSONArray("item");
for(int i=0;i<jr.length();i++)
{
JSONObject jb1 = (JSONObject) jr.get(i);
String title = jb1.getString("title");
// similar for title link and others
JSONObject enclosure = jb1.getJSONObject("enclosure");
JSONObject attributes= enclosure.getJSONObject("#attributes");
String url = attributes.getString("url");
Log.i("....",""+title);
String elemento= jb1.getString("elemento");
// similar for others planeta..
}
} catch (Exception e) {
e.printStackTrace();
}

Try this
JSONObject jObject = new JSONObject(lecturaJsonTusPerlas);
JSONArray jsonArray2 = jObject.getJSONArray("your array key");
for (int i = 0; i < jsonArray2.length(); i++) {
JSONObject jsonObject = jsonArray2.getJSONObject(i);
boolean var1 = jsonObject.getBoolean(atr1);
int var2 = jsonObject.getInt(atr2);
String var3 = jsonObject.getString(atr4);
}
don't initialize string values as null.

You might be getting NullPointerException because these lines:
String atr1 = null;
boolean var1 = jsonObject.getBoolean(atr1);
String atr2 = null;
int var2 = jsonObject.getInt(atr2);
String atr4 = null;
String var3 = jsonObject.getString(atr4);
you're trying to parse with "null" reference.
See atr1, atr2 and atr4; these strings are initialized with "null".

The reason you are getting this error is your top node of json element is object not an JSON Array.
So to begin parsing you need to write something like this
JSONObject jObject = new JSONObject(result);

Related

Android Studio: JSON Parsing

I have an JSON File which I want to parse but don't know how to access it correctly.
It doesn't start with an Object bracket "{" and afterwards a Name like e.g. "actors:" "[" .... ]}
where I would easily create an
JSONObject jObj = new JSONObject(data);
JSONArray jArray = jObj.getJSONArray("actors");
mine looks more like this
[
{
"type": "fuel",
"name": "Aral",
"address": "Somestreet 65",
"lat": 49.8848387,
"lon": 8.6520691 },
{
"type": "amenity",
"name": "Centralstation",
"address": "Centralstreet 20",
"lat": 49.8725,
"lon": 8.628889,
"icon": "somepicture.jpg" },
]
I tried something like
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
//JSONObject jsonObject = new JSONObject(data);
for(int i=0; i< jsonArray.length();i++){
Locations location = new Locations();
JSONObject jRealObject = jsonArray.getJSONObject(i);
location.setName(jRealObject.getString("type"));
location.setName(jRealObject.getString("name"));
location.setName(jRealObject.getString("address"));
location.setName(jRealObject.getString("lat"));
location.setName(jRealObject.getString("lon"));
//location.setImage(jRealObject.getString("icon"));
locationList.add(location);
}
return true;
}
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
return false;
}
But there is an error while parsing it I think it has something to do with "JSONArray jsonArray = new JSONArray("");
can you help me out or point in a direction where I could find my error
Take a look at my GitHub project: Json Response Renderer Android project. This might help you :)
try this....
JSONArray jsonArray = new JSONArray (data);
for(int i=0; i< jsonArray.length();i++){
Locations location = new Locations();
JSONObject jRealObject = jsonArray.getJSONObject(i);
location.setName(jRealObject.getString("type"));
location.setName(jRealObject.getString("name"));
location.setName(jRealObject.getString("address"));
location.setName(jRealObject.getString("lat"));
location.setName(jRealObject.getString("lon"));
locationList.add(location);
}
-if you get a differnt keys use Iterator to get keys like
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
JSONArray jarray=new JSONArray(data);
for (int i=0;i<=jarray.length();i++)
{
JSONObject obj1=jarray.getJSONObject(i);
String address=obj1.getString("type");
String caseno=obj1.getString("name");
String casetype=obj1.getString("address");
}

How to fetch json array inside array in android listview

I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.

org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject

Getting org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject..Where would be code went wrong?This is a program to get values from a live streaming ..complete code is given below..
JSON given
race: {
id: "44708",
track_id: "1",
track: "International",
starts_at: "2016-05-04 06:16:00",
finish_time: "1970-01-01 01:00:00",
heat_type_id: "123",
heat_status_id: "1",
speed_level_id: "5",
speed_level: "Nat Cadet & Junior",
win_by: "position",
race_by: "minutes",
duration: 10,
race_name: "Inkart National Heat",
race_time_in_seconds: 276.336
},
scoreboard: [
{
position: "1",
nickname: "Emily Linscott",
average_lap_time: "90.053",
fastest_lap_time: "60.490",
last_lap_time: "60.490",
rpm: "1225",
first_name: "Emily",
last_name: "Linscott",
is_first_time: "0",
total_races: "6",
racer_id: "1157509",
lap_num: "3",
kart_num: "63",
gap: ".000",
ambtime: "31728819591"
},
Code
protected JSONObject doInBackground(String... urls) {
JSONObject jsonObj = null;
Log.d("TAG","inside doInBackground..");
try {
URL url = new URL("http://daytonamk.clubspeedtiming.com/api/index.php/races/scoreboard.json?track_id=1&key=cs-dev" + kartNumber);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String result = convertInputStreamToString(inputStream);
parseResult(result);
Log.e("Message", "This is a message");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
String result = "";
{
while ((line = bufferedReader.readLine()) != null) {
builder.append( line);
}
return result;
}
}
private JSONObject parseResult(String result) {
JSONObject jsonObj = null;
if (result == null) {
Toast.makeText(Main_Activity.this, "Race not currently running", Toast.LENGTH_LONG).show();
} else {
try {
int number = 0;
jsonObj = new JSONObject("result");
JSONObject race = jsonObj.getJSONObject("race");
int durationInMins = race.getInt("duration");
String win_by = race.getString("win_by");
JSONArray scoreboard = jsonObj.getJSONArray("scoreboard");
Log.d("TAG", "Json value :" + scoreboard);
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
number = data.getInt("kart_num");
while (kartNumber == number) {
int gridPosition = data.getInt("position");
int gap = data.getInt("gap");
int lastLapTime = data.getInt("last_lap_time");
int bestLapTime = data.getInt("fastest_lap_time");
int raceInTime = race.getInt("race_time_in_seconds");
duration = durationInMins * 60 - raceInTime;
if (!(gridPosition == 1)) {
JSONObject dataPreviousGap = scoreboard.getJSONObject(i - 1);
int gapPrev = dataPreviousGap.getInt("gap");
gapUp = gap - gapPrev;
}
if (!(i == scoreboard.length() - 1)) {
JSONObject dataNext = scoreboard.getJSONObject(i + 1);
int gapNext = dataNext.getInt("gap");
gapDown = gapNext - gap;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObj) {
Intent myIntent = new Intent(Main_Activity.this, Display_Activity.class);
try {
JSONObject jsonObje = new JSONObject("result");
JSONArray scoreboard = jsonObje.getJSONArray("scoreboard");
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
myIntent.putExtra("GridPosition", data.getInt("position"));
myIntent.putExtra("LastLapTime", data.getInt("last_lap_time"));
myIntent.putExtra("MinutesToGo", duration);
myIntent.putExtra("BestLapTime",data.getInt("fastest_lap_time"));
myIntent.putExtra("GapUp", gapUp);
myIntent.putExtra("GapDown", gapDown);
}
Just as your logcat reads org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject
Log the response you are getting without parsing the data first. Then you may find out what data types you are dealing with eg: Strings, Integers, Floats,etc.
Post the response here for more help.
EDIT:
This line here jsonObj = new JSONObject("result");
Do this instead jsonObj = new JSONObject(result);
EDIT:
jsonObj = new JSONObject(result);
JSONObject obj = jsonObj.getJSONObject("race");
String id = obj.getString("id");
//do the same for all objects inside race

How to get handle json data with two arrays in android?

I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}

how to access multi array json file?

this is my code below how do i acess this json file check my method it is coreect method to aces json file array and nodes? i want to acess this json file below from my code help me how do i acess this json file formmy code? i dontknow howmany array in json file
{
"status":1,
"message":"",
"data":
{
"school":
[
{
"id":3,
"name":"FG Public School"
},
{
"id":4,
"name":"Fazaia Inter College"}
]
}
}
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(SelectMenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream =
response.getEntity().getContent();
BufferedReader in = new BufferedReader(new
InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object =
data.getJSONObject(i);
// JSONObject category =
object.getJSONObject("Category");
Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("name"));
Log.d("Category name",
Category_name.get(i));
Try This Code
=================================================================
try {
String[] Id,name;
JSONObject json = new JSONObject(str);
JSONObject SubString3 = json.getJSONObject("data");
Log.e(SubString3.toString(),"SubString3");
JSONArray Array = SubString3.getJSONArray("school");
Id = new String[Array.length()];
name =new String[Array.length()];
for(int i=0;i<=Array.length();i++)
{
Id[i]= Array.getJSONObject(i).getString("id");
Log.e(Id[i].toString(),"Id[i]");
name[i]= Array.getJSONObject(i).getString("name");
Log.e(name[i].toString(),"name[i]");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Category object is not present inside the Json file
you can try following
JSONObject json = new JSONObject("str");
JSONObject data = json.getJSONObject("data");
JSONArray school = json.getJSONArray("school");
for (int i = 0; i < data.length(); i++) {
JSONObject object = school.getJSONObject(i);
long id = Long.parseLong(object.getString("id"));
String name = object.getString("name");
JSONObject category = new JSONObject();
category.put("id");
category.put("name");
}
First you need to fetch an OBJECT of the whole JSON because it's in '{' '}'. Then you need to fetch an object again with the name "data" because it is in '{' '}'. And only then should you fetch the array named "school".
JSONObject json = new JSONObject(str);
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("school");

Categories

Resources