Parsing a flat JSON array with no indice - java

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();
}

Related

How to use JSON to get value?

Log.d("Hot Text:", response.toString());
try {
JSONArray array = response.getJSONArray("rows");
JSONObject jsonObject = array.getJSONObject(0);
JSONArray a = jsonObject.getJSONArray("elements");
JSONObject js = a.getJSONObject(0);
JSONObject b = js.getJSONObject("distance");
value = b.getString("value");
Log.d("TAG", "title:" + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
how to get "value" to storage for other space? thank u
You can do like this:
String text;
int value;
try {
JSONObject jsonObject = new JSONObject(body);
JSONArray rowArray = jsonObject.optJSONArray("rows");
if(rowArray.length() > 0){
JSONObject row = rowArray.optJSONObject(0);
JSONArray elementArray = row.optJSONArray("elements");
if(elementArray.length() > 0){
JSONObject element = elementArray.optJSONObject(0);
JSONObject distance = element.optJSONObject("distance");
text = distance.optString("text");
value = distance.optInt("value");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("text", text);
Log.e("value", "value : " + value);

JSON parse multidimensional array volley

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);

Parse json string to json array? [duplicate]

This question already has answers here:
Convert string to JSON array
(10 answers)
Closed 5 years ago.
i need help to convert json string to json array as i given below
{"level":[{"id":"1","name":"first","time":"00:02:00"},{"id":"2","name":"second","time":"00:03:00"},{"id":"3","name":"math","time":"00:03:00"},
{"id":"4","name":"language ","time":"00:03:00"},{"id":"5","name":"sport","time":"00:04:00"}]}
to use it in android studio
Try this
try
{
JSONObject resObject = new JSONObject("your json response");
JSONArray jsonArray = resObject.getJSONArray("level");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i("id", "" + jsonObject.getString("id"));
Log.i("name","" + jsonObject.getString("name"));
Log.i("time", "" + jsonObject.getString("time"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
OUTPUT
Try this
try {
JSONObject jsonObject=new JSONObject(yourresponsestring);
JSONArray jsonArray=new JSONArray(jsonObject.getJSONArray("level"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String id=jsonObject1.getString("id");
String name=jsonObject1.getString("name");
String time=jsonObject1.getString("time");
}
} catch (JSONException e) {
e.printStackTrace();
}
You can try below code to convert the data to JSON:
try {
JSONObject jsonObject = new JSONObject("{\"level\":[{\"id\":\"1\",\"name\":\"first\",\"time\":\"00:02:00\"},{\"id\":\"2\",\"name\":\"second\",\"time\":\"00:03:00\"},{\"id\":\"3\",\"name\":\"math\",\"time\":\"00:03:00\"}, {\"id\":\"4\",\"name\":\"language \",\"time\":\"00:03:00\"},{\"id\":\"5\",\"name\":\"sport\",\"time\":\"00:04:00\"}]}");
JSONArray level = jsonObject.getJSONArray("level");
for (int i = 0; i < level.length(); i++) {
JSONObject data = level.getJSONObject(i);
String id = data.getString("id");
String name = data.getString("name");
String time = data.getString("time");
Log.d("JSONDATA--->", "Data at: " + i + " " + id + ":" + name + ":" + time);
}
} catch (JSONException e) {
e.printStackTrace();
}

how to access jsonarray elemennts

#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.

How to getting multiple tables in json from sql to android

i try to get multiple table from json, i have two tables ( hotline and other ) , i can get data from hotline table, but cannot get from other table
in my php (json):
{"hotline":[{"id":"2","name_hotline":"Tourist Police","phone_hotline":"192"},{"id":"6","name_hotline":"Water","phone_hotline":"1199"}]}{"other":[{"id":"1","name_other":"Lao National Tourism Administration","phone_other":"+85621212248 ","latitude_other":"0","pic_other":"","longtitude_other":"0"},{"id":"2","name_other":"Tourism Police Department","phone_other":"+85621251128 ","latitude_other":"0","pic_other":"","longtitude_other":"0"}]}
MainActivity.java :
InputStream objInputStream = null;
String strJSON = "";
try {
HttpClient objHttpClient = new DefaultHttpClient();
HttpPost objHttpPost = new HttpPost("http://192.168.1.102/emergencycall/php_get_data.php");
HttpResponse objHttpResponse = objHttpClient.execute(objHttpPost);
HttpEntity objHttpEntity = objHttpResponse.getEntity();
objInputStream = objHttpEntity.getContent();
Log.d("Emergency", "Connected HTTP Success !");
} catch (Exception e) {
Log.d("Emergency", "Error Connect to : " + e.toString());
}
try {
BufferedReader objBufferesReader = new BufferedReader(new InputStreamReader(objInputStream, "UTF-8"));
StringBuilder objStrBuilder = new StringBuilder();
String strLine = null;
while ((strLine = objBufferesReader.readLine()) != null) {
objStrBuilder.append(strLine);
}
objInputStream.close();
strJSON = objStrBuilder.toString();
Log.d("Emergency", "Connected JSON Success !");
} catch (Exception e) {
Log.d("Emergency","Error Convert To JSON :" + e.toString() );
}
try {
JSONObject object = new JSONObject(strJSON);
JSONArray objJSONArray = object.getJSONArray("hotline");
JSONArray objJSONAraay2 = object.getJSONArray("other");
for (int i = 0; i < objJSONArray.length(); i++) {
JSONObject objJSONObject = objJSONArray.getJSONObject(i);
strNameHotlineMySQL = objJSONObject.getString("name_hotline");
strPhoneHotlineMySQL = objJSONObject.getString("phone_hotline");
}
for (int j = 0; j < objJSONAraay2.length(); j++) {
JSONObject objJSONObject1 = objJSONAraay2.getJSONObject(j);
strNameHospitalMySQL = objJSONObject1.getString("name_other");
strPhoneHospitalMySQL = objJSONObject1.getString("phone_other");
long insertID4 = objHotlineTable.addDataFromSQLiteHospital(strNameHospitalMySQL, strPhoneHospitalMySQL, strPicHospitalMySQL);
}
} catch (Exception e) {
Log.d("Emergency","Error syncdata to SQLite :" + e.toString() );
}
and i get an error in Logcat:
: Error syncdata to SQLite :org.json.JSONException: No value for other
Your json data format is not correct. Json data format should be like this:
{
"hotline":[
{
"id":"2",
"name_hotline":"Tourist Police",
"phone_hotline":"192"
},
{
"id":"6",
"name_hotline":"Water",
"phone_hotline":"1199"
}
],
"other":[
{
"id":"1",
"name_other":"Lao National Tourism Administration",
"phone_other":"+85621212248 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
},
{
"id":"2",
"name_other":"Tourism Police Department",
"phone_other":"+85621251128 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
}
]
}
And than,
You can use "Retrofit" and "gson" for http request and object mapping.

Categories