JSON parse multidimensional array volley - java

I stumbled upon a problem while trying to parse a JSON in my android app. In the screenshot below I provided the structure of the JSON. I can't get further than getting the "geometry" JSONObject. Eventually I need an array containing LatLng's for each "feature".
If anyone can point me in the right direction I would really appreciate it.
This is my code.
//gets the area's out of the JSON
JsonObjectRequest LosLoopJson = new JsonObjectRequest(losloopURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray features = response.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject Area = features.getJSONObject(i);
for (int x = 0; x < features.length(); x++) {
JSONObject geometry = Area.getJSONObject("geometry");
Double[][][] coordinates = geometry.get("coordinates");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
requestQueue.add(objectrequest);
And here is my JSON structure:
Thanks in advance!

Coordinate is a json array and each element in it, also contains a json array. So you've to iterate over the coordinate object.
JSONArray coordinates = geometry.get("coordinates");
for(int i = 0; i < coordinates.size(); i++)
JSONArray coord = coordinates.get(i);

Try this:-
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("features");
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("geomerty")){
JSONArray jsonArray1 = jsonObject1.getJSONArray("geomerty");
for (int j = 0; j <= jsonArray1.length(); j++){
if (jsonObject1.has("coordinates")){
JSONArray jsonArray2 = jsonObject1.getJSONArray("coordinates");
for (int k = 0; k <= jsonArray2.length();k++){
JSONArray jsonArray3 = jsonArray2.getJSONArray(k);
for (int l =0; l <= jsonArray3.length(); l++){
Log.d("ABC", String.valueOf(jsonArray3.getDouble(l)));
}
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Thanks for all the help, I got it working using this code:
//gets the area's out of the JSON
JsonObjectRequest LosLoopJson = new JsonObjectRequest(losloopURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray features = response.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject Area = features.getJSONObject(i);
JSONObject geometry = Area.getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
JSONArray AreaCoordinates = coordinates.getJSONArray(0);
//Log.d("Debug", "Feature: " + String.valueOf(i + 1));
for (int y = 0; y < AreaCoordinates.length(); y++) {
//Log.d("Debug", "Coordinate: " + String.valueOf(y + 1));
JSONArray DoubleCoordinate = AreaCoordinates.getJSONArray(y);
Double latitude = DoubleCoordinate.getDouble(1);
Double longitude = DoubleCoordinate.getDouble(0);
LatLng coordinate = new LatLng(latitude, longitude);
LosLoopGebied.add(coordinate);
}
losloopgebieden.add(LosLoopGebied);
LosLoopGebied.clear();
}
//PlaatsLosLoopGebieden();
//Log.d("Debug", "Heeft de losloopgebieden opgehaalt uit JSON");
//Log.d("Debug", "Er zijn " + String.valueOf(LosLoopGebied.size()) + " coordinaten opgehaalt");
Log.d("Debug", "Er zijn " + String.valueOf(losloopgebieden.size()) + " opgehaalt uit JSON");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
requestQueue.add(LosLoopJson);

Related

Parse json in Java android studio

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

android JSONException index 1 out of range [0..1] (Parse 2 json arrays inside 1 loop)

I have code like this, the value of jArrAnswer is
[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}]
the result from jArrAnswer.length() is 4
but why I got error
org.json.JSONException: Index 1 out of range [0..1).
try {
JSONArray jArrAnswerid = new JSONArray(answerid);
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i);
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswerid.getString("answerid");
String ans= jObjAnswer.getString("answer");
GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid);
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.
Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().
Print the jArrAnswerid.size() and check.
Try this
try {
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswer.getString("answerid");
String ans= jObjAnswer.getString("answer");
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
provided "answer" is your json array response
Try
String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String answerId = jsonObject.getString("answerid");
String answer = jsonObject.getString("answer");
//Use answerId and answer
}
}
} catch(JSONException e) {
e.printStackTrace();
}

Android Arraylist to JSONObject

Im trying to take the values from the ArrayList and put in to an JSONObject. I have written the below code but it does only put the last value from arraylist to jsonobject
I am trying to achieve this out put.
{"lstContacts":"array_value"},{"lstContacts":"array_value"},{"lstContacts":"array_value"}
This is my code
ArrayList<String> tokens;
JSONObject contactsObj;
..
...
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("ContactToken", tokens.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
}
});
Try this:
JSONObject contactsObj = new JSONObject();
JSONArray contactsArray = new JSONArray();
try {
for (int i = 0; i < tokens.size(); i++) {
JSONObject contact = new JSONObject();
contact.put("ContactToken", tokens.get(i));
contactsArray.put(i, contact);
}
contactsObj.put("contacts", contactsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
The result jsonStr will look like this:
{
"contacts":[
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
}
]
}
You are overriding the object because u are using an JsonObject for an ArrayList, the solution is to use an JsonArray contactObj in your case
JSONArray contactsObj;
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put(i, tokens.get(i));
}
JSONObject contactsObj = new JSONObject();
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("lstContacts" + String.valueOf(i), tokens.get(i));
}
// done...
contactsObj.put("ContactTokens", new JSONArray(tokens));
Is probably closest to what you're looking for. You don't even need to loop for this.
This will give you the object
{
"ContactTokens":["token1","token2","token3"...]
}

Parsing a flat JSON array with no indice

I am scratching my head to figure out how to parse the following JSON object.
[
{
"result": true,
"response": "Successfully got list of users in radius of 10km"
},
{
"username": "elize",
"photo": "http://www.embedonix.com/apps/mhealth/images/elize/elize.png"
},
{
"username": "mario",
"photo": "http://www.embedonix.com/apps/mhealth/images/mario/mario.png"
}
]
This is I guess a single index json array. The first part tells that the operation of building the json object was ok.
Then there are pairs of username and photo which I have to parse them and put them in a list:
public class User {
private String mName;
private String mPhotoURl;
public User(String name, String url)
{
///
}
}
So if the first entry of json is result -> true I should have a ArrayList<User>.
I tried to do the following but it always raises the JSONParse exception:
try {
JSONObject json = new JSONObject(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONArray obj = json.getJSONArray(String.valueOf(i));
Log.i(TAG, i + " username: " + obj.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Just try this way
try {
JSONArray jsonArray = new JSONArray(data);
int length = jsonArray.length();
for (int i = 1; i < length; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
if(i==0){
Log.i(TAG, i + " result: " + obj.getString("result"));
Log.i(TAG, i + " response: " + obj.getString("response"));
}else{
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try Code...something like this..
try {
JSONArray json = new JSONArray(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONObject childObject = json.getJSONObject(i);
if(i==0){
String result = child.getBoolean("result");
String resp = child.getString("response");
} else {
String username = child.getString("username");
String photo = child.getString("photo");
Log.i(TAG, i + " username: " + username);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

How to parse JSON Array of String in android

this is the response from the server
{"route":[1,2,3,4,5,6]}
This is my code:
try{
String d = json.getString("route");
}
}catch(JSONException je){
}
and im getting NullPointerException.
please help me.
This is my Server Response, Now Give me the solution
Link -> http://ajax.tpksym.cloudbees.net/route/route14
It should be like:
JSONObject jsonResult = new JSONObject("{\"route\":[1,2,3,4,5,6]}");
JSONArray array = jsonResult.getJSONArray("route");
for (int i = 0; i < array.length(); i++) {
int data = array.getInt(i);
}
....
try {
String jsonString = "{\"route\":[1,2,3,4,5,6]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("route");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getInt(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi as yours json is as follows
{
"route": [
1,
2,
3,
4,
5,
6
]
}
so do as follows
String jsondata = "{\"route\":[1,2,3,4,5,6]}";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Integer data = jarray.getInt(i);
System.out.println("data=="+data);
}
as you gave the link http://ajax.tpksym.cloudbees.net/route/route14
and data seems there coming as in double i.e. 13.56 etc
so use as follows
String jsondata = "JSON DATA FROM SERVER";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Double data = jarray.getDouble(i);
}

Categories