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.
Related
I am trying to get all the species result from the first url but sadly, my for loop can only retrieve one species from my first url and I don't know what's the correct logic here. Hope you can help me. I know the problem is my for loop but I don't know how to construct it correctly. Sorry. Newbie here.
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?species_name="
+ search_species;
pDialog.setMessage("Loading data...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("tem");
for(int i = 0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
species_id = o.getString("localname");
common = o.getString("name");
scientific = o.getString("scientificname");
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?speciesid=" + species_id;
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("locationid", c.getString("locationid"));
map.put("brgy", c.getString("brgy"));
map.put("town", c.getString("town"));
map.put("latitude", c.getString("latitude"));
map.put("longitude", c.getString("longitude"));
map.put("speciesid", local);
map.put("flowercolor", c.getString("flowercolor"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
This is my getHttpGet:
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
and this is the PHP file:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$species_name = $_GET['species_name'];
$sql = "SELECT * from tbl_species WHERE CONCAT_WS(name, localname,
scientificname, familyname, flowercolor, leafshape) LIKE '%$species_name%'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
$arr['aaData'] = array();
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode(array('tem' => $tem));
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
Specifically, my for loop can only get the first species, after getting that, the for loop stops to get the others. I don't know what's wrong and what I should change. I'm creating a project that can search a species by name, by color, by shape etc.
Just a guess but maybe because you use the same int in both for loops
for(int i = 0; i<array.length(); i++)
for(i = 0; i < data.length(); i++){
You have a NetworkOnMainThreadException and your app crashes when you handle the second url.
You could have told us of the crash.
You should execute all network/internet code in a thread or asynctask.
You must have 2 variables to save the values in PHP file.and use array_push for save all values in an array
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?type=first&species_name="
+ search_species;
.
.
.
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?type=tow&speciesid=" + species_id;
try {.....
and in PHP file
$type = $_GET['type'];
$response1 = array();
$response2 = array();
.
.
.
while($row[] = $result->fetch_assoc()) {
if (type ==="fist"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}elseif (type ==="tow"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}
}////end while
if (type ==="fist"){
echo $response1;
}elseif(type1 ==="tow"){
echo $response2;
}
.
.
.
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");
}
i made a asynctask routine to comunicate to all my webservices that looks as follows:
protected String[] doInBackground(String... params) {
String parameterString = params[0];
// effectieve http request met de parameters toegevoegd
HttpClient client = new DefaultHttpClient();
HttpGet aanvraag = new HttpGet(server + parameterString);
// foutanalyse van de http request
try
{
HttpResponse antwoord = client.execute(aanvraag);
StatusLine statuslijn = antwoord.getStatusLine();
int statuscode = statuslijn.getStatusCode();
if(statuscode != 200){
Log.i("statuscode verzending", "statuscode= "+ statuscode);
return null;
}
InputStream jsonStream = antwoord.getEntity().getContent();
BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String lijn;
while((lijn = reader.readLine())!= null){
builder.append(lijn);
}
String jsonData = builder.toString();
// hier beginnen we met de json data te ontmantelen
JSONArray json = new JSONArray(jsonData);
String[] data = new String[35];
Log.i("jsonparser", "lengte geretourde data " + json.length());
for (int i = 0; i < json.length(); i++)
{
data[i] = json.getString(i).toString();
}
return data;
}
catch (ClientProtocolException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
i use the routine everytime i connect to a webservice for my app, (i have about 15 of them)
all these webservices are made (and used) by the programs my software supplier made
now i would like to connect to them with my android app
some of them are working
others don't
what i found out already in my search for this failure:
some jsondata is returned in the form of:
[
"42416",
" ",
" ",
" "
]
other webservices return data as:
true
but the ones i am strugling with the most are looking like:
{
"z00": "1 ",
"z01": 10000,
"z02": "18/06/2010",
"z03": "A",
"z04": "0000",
"z05": 7735,
"z06": "VANNUYSE BVBA",
"z07": "DEEFA",
"z08": 17170,
"z09": "AFLEVEREN HELI IN GEBRUIK",
"z10": "0000",
"z11": "8770 ",
"z12": "INTER ",
"z13": "HELI ",
"z14": "CPCD25 - C240 ",
"z15": "48182 ",
"z16": "",
"z17": "N",
"z18": "0030",
"z19": 0,
"z20": "X",
"z21": " ",
"z22": "J",
"z23": "",
"z24": 0,
"z25": "22/06/2010",
"z26": 16854,
"z27": 0,
"z28": "AFLEVEREN IN GEBRUIK",
"z29": " "
}
how should i form my asynctask routine so she is able to work for all routines?
because my routine works fine now for the first type of data but at 3th type i get an error (didn't tried yet for 2nd type) :
JSONObject cannot be converted to JSONArray
thanks already for al your help guys
If you don't know what(jsonObject or jsonArray) is coming, you may try something like this:
try {
JSONObject jsonObject = new JSONObject(jsonData);
// handle jsonObject
} catch (JSONException e) {
// Try to parse it to a JSONAray.
// Also you can check the exception message here to determine if jsonArray conversion is wanted
try {
JSONArray jsonArray = new JSONArray(jsonData);
// handle jsonArray
} catch (JSONException e) {
// something which is not JsonObject or JsonArray!
}
}
Or try this:
Object jsonAsObject = new JSONTokener(jsonData).nextValue();
if (jsonAsObject instanceof JSONObject) {
// it is JSONObject
JSONObject jsonObject = (JSONObject) jsonAsObject;
} else if (jsonAsObject instanceof JSONArray) {
// it is JSONArray
JSONArray jsonArray = (JSONArray) jsonAsObject;
}
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);
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");