JSON array retrieve value by name - android

public void onResponse( String response ){
JSONArray jsonArray ;
try{
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);
}
catch(JSONException e){
e.printStackTrace();
}
}
and my json file is
[
{
"0":"1",
"1":"Adarsh",
"id":"1",
"name":"Adarsh"
},
{
"0":"2",
"1":"Asif",
"id":"2",
"name":"Asif"
},
{
"0":"3",
"1":"Baba",
"id":"3",
"name":"Baba"
},
{
"0":"4",
"1":"Beeta",
"id":"4",
"name":"Beeta"
}
]
In my application it doesn't retrieve the value for "name" instead showing error toast.

jsonArray has not been initialised
jsonArray = new JSONArray("yourjson");
String name = jsonArray.getJSONObject(1).getString("name");

First change your string response to json response like this:
JsonArray jarray=new JsonArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);

Here you are trying to fetch data from string as per your comment so need to convert in to json first like this
public void onResponse( String response ){
try{
JSONArray jsonArray= new JSONArray(response);
Log.d("JsonArray", jsonArray.toString());
JSONObject jsonObject = jsonArray.getJSONObject(1);
String result = jsonObject.getString("name");
t.setText(result);
}
catch (Throwable t) {
Log.e("ERROR", "Wrong Json format");
}
catch(JSONException e){
e.printStackTrace();
}
}

Related

How can i get data from array in array retrofit2

Please take this reference
want to get appointment arraylist to inflate listview, i reached to call_detail but how can i get appointment array with retrofit2 gsonConverter
{
"patient":{},
"medicine":[
],
"call_detail":[
{
"created_on":"2016-01-22 06:06:00",
"call_type":"",
"rbs":"10",
"temp":"",
"provisional_diagnosis":"yes",
"follow_up_call_schedule":"",
"follow_up_call_date":"1970-01-01",
"reports":[
],
"medicalreference":[
],
"services_comment":"",
"health_consultation":"",
"appointment":[
{
"doctor_id":"28",
"clinic":"",
"hospital":"Shwe Nyaung Pin specialist ",
"name":"Dr.Nyein Mon Yu",
"app_date":"2016-01-21",
"app_time":"1:00 AM TO 1:00 AM"
}
]
}
],
"status":"true"
}
Try this..
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("call_detail");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObjectCall=jsonArray.getJSONObject(i);
JSONArray jsonArrayAppointment=jsonObjectCall.getJSONArray("appointment");
for (int j=0;j<jsonArrayAppointment.length();j++)
{
JSONObject jsonObjectApp=jsonArrayAppointment.getJSONObject(j);
String doctor_id=jsonObjectApp.getString("doctor_id");
String clinic=jsonObjectApp.getString("clinic");
String hospital=jsonObjectApp.getString("hospital");
String name=jsonObjectApp.getString("name");
String app_date=jsonObjectApp.getString("app_date");
String app_time=jsonObjectApp.getString("app_time");
System.out.println("doctor_id"+doctor_id);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
To get appointment array try below code. Here jsonString is your given json in question:
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONArray appointmentArray=jsonObject.getJSONArray("call_detail").getJSONObject(0).getJSONArray("appointment");
Log.d("appointmentArray",appointmentArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}

JSON array not being parsed [duplicate]

This question already has an answer here:
JSON array parsing in android
(1 answer)
Closed 7 years ago.
I have a JSON response in this format:
{
"success": true,
"categories": [{
"id": "774",
"name": "1"
}, {
"id": "774",
"name": "1"
}]
}
And I am parsing it like this:
try {
JSONObject obj = new JSONObject(response);
String success = String.valueOf(obj.getBoolean("success"));
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
But I only get the value of success. What I'm doing wrong here?
Parse as below -
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
correct json key
JSONArray arr = obj.getJSONArray("checkouts");
replace by:
JSONArray arr = obj.getJSONArray("categories");
DO like this,
if (!result.equalsIgnoreCase("")) {
try {
JSONObject _jsonObject = new JSONObject(result);
boolean json = false;
json = _jsonObject.getBoolean("Status");
JSONArray jsonArray1 = _jsonObject.getJSONArray("categories");
for (int i=0; i<jsonArray1.length(); i++) {
JSONObject jsonObject = jsonArray1.getJSONObject(i);
String name = jsonObject.getString("name");
String id = jsonObject.getString("id");
}
} catch (Exception e) {
Utils.printLoge(5, "error parse json", "--->" + e.getMessage());
return "ERROR";
}
}

JSON parsing android json arrays and json object

I'm getting a json response through volley, the response is as following :
{
"status":"success",
"message":"Request Successfull",
"messagetitle":"Success",
"show":"false",
"goback":"false",
"companies":[
{
"id":"14",
"category":{
"id":"1",
"name":"test"
},
"subcategory":{
"id":"1",
"name":"test",
"image":"https:\/\/page.com\/page\/uploads\/pagepics\/test\/testpics\/test.jpg"
},
"name2":"Company",
"location":null,
"logo":"https:\/\/page.com\/test\/testp\/testpics\/logo.png",
"picture":"https:\/\/page.com\/test\/",
"facebook":"https:\/\/www.facebook.com\/test",
"instagram":"",
"twitter":"",
"telephone1":"+9611990454",
"telephone2":"+961000000",
"address":"Lebanon",
"longitude":"0",
"latitude":"0",
"website":"www.website.com",
"email":"",
"desc":"asdasdas das das das dasda das das das dsadasdsadasdsad asd asd asd asd sad sa as das dsa asd das a a",
"user":{
"id":"21",
"name":"X Y"
},
"status":"1"
},
{
"id":"4",
"category":{
"id":"1",
"name":"test"
},
"subcategory":{
"id":"1",
"name":"test",
"image":"https:\/\/page.com\/test\/testp\/testpics\/test\/testphoto\/test.jpg"
},
"name2":"Your Company",
"location":null,
"logo":"",
"picture":"https:\/\/page.com\/test\/",
"facebook":"",
"instagram":"",
"twitter":"",
"telephone1":"",
"telephone2":"",
"address":"",
"longitude":"0",
"latitude":"0",
"website":"",
"email":"",
"desc":"",
"user":{
"id":"1",
"name":"X Y"
},
"status":"1"
}
]
}
I'm trying to get all "image" and "name2" objects from the response. Here is my java code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
link, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d("Request", response.toString());
try {
jarray1 = response.getJSONArray("subcategory");
for(int i=0;i<jarray1.length();i++)
{
JSONObject object = (JSONObject) jarray1.get(i);
String url = object.getString("image");
String name= object.getString("name2");
Toast.makeText(getBaseContext(),url+"\n"+name,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Well it's giving me wrong info, any help please ?
You can't directly access inner objects in JSON, according to your json format you have to first get JSON Array of companies
JSONArray companiesArray = response.getJSONArray("companies");
Then get elements of the array
for(int i=0;i<companiesArray .length();i++){
JSONObject object = (JSONObject) companiesArray.get(i);
// Now get subcategory information as JSONObject
JSONObject subcategoryObject =object .getJSONObject("subcategory");
// Now you can get image and name from subcategoryObject
String url = subcategoryObject.getString("image");
String name= subcategoryObject.getString("name2");
}
JSONArray jAry=response.getJSONArray("companies");
for(int k=0;k<jAry.size();k++)
{
String url = jAry.getJSONObject(k).getString("image");
String name= jAry.getJSONObject(k).getString("name2");
}
you have to use like above code to get the output from the json. I have given it for example
I figured it out :
try {
// response.getString("status");
jarray = response.getJSONArray("companies");
company_name=new String[jarray.length()];
for(int i=0;i<jarray .length();i++){
JSONObject object = (JSONObject) jarray.get(i);
// Now get subcategory information as JSONObject
// JSONObject subcategoryObject =object .getJSONObject("subcategory");
// Now you can get image and name from subcategoryObject
company_name[i]= object.getString("name2");
}
public void SendPost() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your_php_url");
try {
httppost.setEntity(new UrlEncodedFormEntity(postdata)); // Here postdata is BasicNameValuePair array with data to send
HttpResponse httpResponse = httpclient.execute(httppost);
String result = EntityUtils.toString(httpResponse.getEntity());
GetResponce(result);
} catch (UnsupportedEncodingException ex) {
} catch (IOException ex) {
} catch (JSONException ex) {
}
}
public void GetResponce(String responce) throws JSONException {
JSONObject myObject = new JSONObject(responce);
JSONArray companies = myObject.getJSONArray("companies");
String[] urls = new String[companies.length()];
String[] names = new String[companies.length()]; //Here i'm initializing the arrays
for (int i = 0; i < companies.length(); i++) {
JSONObject object = companies.getJSONObject(i);
JSONObject secondObject = object.getJSONObject("subcategory");
urls[i] = secondObject.getString("image");
names[i] = object.getString("name2");
}
}

I need to receive data from server in JSON format in my Android app

Here is my JSON
{
"keys": [
"10_Ultimate",
"20_Yemensoft"
]
}
When I hit directly in the Url I am getting correct response but not from Android. Also I have seen in jsonlint the JSON format is correct. But I am getting following message:
org.json.JSONException: Unterminated array at character 11 of
[B#41c16df8
when i hit the Url
http://192.168.0.103:8080/AndroidRest/financial/finList
I am getting correct json response Also i validated in jsonlint.com
{
"keys" : [ "10_Ultimate", "20_Yemensoft" ]
}
when i try to deserialize from android it saysorg.json.JSONException: Unterminated array at character 11
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
JSONObject jsnObj = new JSONObject();
String res = response.toString();
try {
JSONObject json = new JSONObject(res);
JSONArray jsnArry = json.getJSONArray("keys");
for (int i = 0 ; i < jsnArry.length() ; i++){
jsnObj = jsnArry.getJSONObject(i);
}
Log.d("jsnObj",jsnObj.toString());
Log.d("jsnArry",jsnArry.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("The Positive are",res);
}
You can try this (I have tested):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonString = "{\n" +
" \"keys\" : [ \"10_Ultimate\", \"20_Yemensoft\" ]\n" +
"}";
JSONObject jsnObj = new JSONObject();
try {
JSONObject json = new JSONObject(jsonString);
JSONArray jsnArry = json.getJSONArray("keys");
for (int i = 0 ; i < jsnArry.length() ; i++){
jsnObj.put(String.valueOf(i), jsnArry.getString(i));
}
Log.d("jsnObj", jsnObj.toString());
Log.d("jsnArry",jsnArry.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("The Positive are", jsonString);
}

how can decode json data form api in android?

I am geting JSON data getting from web service. Below is my code.
How can I decode the json data?
{
"response": [
{
"last_name": "Test",
"id": 279711390,
"first_name": "Vishnu",
"sex": 2,
"photo_50": "https://vk.com/images/camera_50.gif"
}
]
}
How can I parse it? Thanks.
You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.
Example:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("last_name");
String firstName = obj.getString("first_name");
//same for all other fields in responseArray
MyResponse myResp = new MyResponse();
myResp.setFirstName(firstName);
myResp.setLastName(lastName);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class MyResponse{
public String firstName="";
public String lastName="";
//all other fields and getter setters
}
Hope this helps.
You can parse JSON using this code:
str="<The Json>"
try {
JSONObject jObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
String lastName;
for (int i = 0; i<menuObject.length(); i++) {
lastName=menuObject.getJSONObject(i).getString("last_name").toString();
...
}
catch (JSONException e) {
e.printStackTrace();
}
Use this code :-
String string = "Your Json"
try {
JSONObject jsonObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
//no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources