My json is like this
{
"results": [{
"syllabus": "CBSE",
"grade": "5",
"subject": "Kannada",
"topic": "Grammar Level 1",
"id": 28
}]
}
Using Volley
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
Your Json have an object and then array.. try like this
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONOArray array = response.getJSONArray("results")
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < array.length(); i++) {
JSONObject person = (JSONObject) array
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
if (!result.equalsIgnoreCase("")) {
try {
JSONObject jsonObject = new JSONObject(result); //result is what you get responce
JSONArray jsonArray = jsonObject.optJSONArray("results");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String syllabus = jsonObjects.optString("syllabus");
Int grade = jsonObjects.optInt("grade");
String subject = jsonObjects.optString("subject");
String topic = jsonObjects.optString("topic");
Int id = jsonObjects.optInt("id");
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} catch (Exception e) {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
Related
I am using Volley in my project for handling network requests. Here is a sample JSON my server returns when it has data then fatch otherwise give error
{
"message_status": true,
"data": [
{
"message_id": "88",
"message_text": "hi,",
"message_link": "0",
},
}
{
"message_status": false,
"message": "Message not available!"
}
this is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_msg,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data") && !jsonObject.isNull("data")) {
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("true")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
}
setupListview();
} else {
// get message using error key
String error = "Response : " + success + " = " + message;
Toast.makeText(ChatActivity.this, error, Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(ChatActivity.this, "data not available", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
when data have no value then show no item message but its give server error
Try this:
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray != null || jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
//loading.setVisibility(View.GONE);
}
setupListview();
} else {
// get message using error key
Toast.makeText(ChatActivity.this, "error 1" + message + success, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
I faced with the problem while trying parse JSON array and list all values it has, I have the following JSON format
{
"sdd": {
"token":"1",
"details":[{
"type":"SOME_TYPE",
"l":,
"expiration_date":"12\/2020",
"default":true,
"expired":false,
"token":"1"
}]
}
}
JSON output I have
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("ssd");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
Log.e(TAG, "response" + jobj.getString("token"));
Log.e(TAG, "response" + jobj.getString("details"));
}
} catch(Exception e) { e.printStackTrace(); }
}
and in the log cat I getting org.json.JSONException: No value for ssd this output
You have typo. Not ssd but sdd. And also sdd is not array, but object.
So you must write like:
JSONObject jb = response.getJSONObject("sdd");
Full parsing code will be like:
public void onResponse(JSONObject response) {
try {
JSONObject sdd = response.getJSONObject("sdd");
JSONArray details = sdd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject jobj = details.getJSONObject(i);
Log.e(TAG, "response-type:" + jobj.getString("type"));
Log.e(TAG, "response-token:" + jobj.getString("token"));
Log.e(TAG, "response-expiration_date:" + jobj.getString("expiration_date"));
Log.e(TAG, "response-default:" + jobj.getBoolean("default"));
Log.e(TAG, "response-expired:" + jobj.getBoolean("expired"));
}
} catch(Exception e) { e.printStackTrace(); }
}
Also, let me suggest you to use gson this library will help you deserialize your json representations.
ssd is an object.
You can get the array as follows:
JSONObject jo = response.getJSONObject("sdd");
JSONArray ja = jo.getJSONArray("details");
hi you must json file isn't create
is create :
{ "sdd":{
"token":"1",
"details":[
{
"type":"SOME_TYPE",
"expiration_date":"12/2020",
"default":true,
"expired":false,
"token":"1"
}
] } }
after you can get data from code :
public void onResponse(JSONObject response) {
try {
JSONObject ssd = response.getJSONObject("ssd");
JSONArray details = ssd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject obj = details.getJSONObject(i);
Log.e(TAG, "response" + obj.getString("type"));
Log.e(TAG, "response" + obj.getString("expiration_date"));
Log.e(TAG, "response" + obj.getBoolean("default"));
Log.e(TAG, "response" + obj.getBoolean("expired"));
Log.e(TAG, "response" + obj.getString("details"));
}
}catch (Exception e){e.printStackTrace();}
}
I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?
private void jsonParse() {
String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject location = jsonArray.getJSONObject(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Json response example
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Use this piece of code.
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray location = jsonObject.getJSONArray(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Its not a JSONArray its a JSONObject.
First get the location from JSONObject.
String location_value=response.get("location");
JSONObject location=new JSONObject(location_value);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
I'm trying to read my data from my localhost to Android Studio. I have used volley to do this. I'm having issue getting the values from my json. Here's my json.
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Here's my code in Android.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(urlJsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String username = response.getString("username");
String section = response.getString("section");
String year = response.getString("year");
jsonResponse = "";
jsonResponse += "Username: " + username + "\n\n";
jsonResponse += "Section: " + section + "\n\n";
jsonResponse += "Year: " + year + "\n\n\n";
txtView.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Appreciate your help.
JSONArray parentArray = response.getJSONArray("studentList");
if (parentArray.length() == 0) {
//no students
} else {
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String username = finalObject.getString("username");
String password = finalObject.getString("password");
String section = finalObject.getString("section");
String year = finalObject.getString("year");
}
}
this will loop through every student in "studentList"
make sure to import JSONArrayimport org.json.JSONArray;
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Structure of your JSON response is an Object containing a list, which contains an object of type student
which contains username & password, where as you are directly trying to get username from outer object.
String username = response.getString("username");
Firstly You need to extract Object from List then access username.
JsonArray jsonArr = response.getJSONArray("studentList");
JsonObject studentObj = jsonArr.get(0);
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject.getJSONArray("studentList");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String username = jsonObject1.getString("username");
String section = jsonObject1.getString("section");
String year = jsonObject1.getString("year");
Toast.makeText(MainActivity.this, username + " " + section + " " + year, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps
I'm unable to fetch from this type of JSON, I'm confused in how to get data from inside of JsonObject, I got the value of "dealer_name", "phone_no" and "address" but I'm not getting the value of other.
This is my Solution.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
urlLink, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("suraj", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
String name = response.getString("dealer_name");
String phone_no = response.getString("phone_no");
String add = response.getString("address");
JSONObject phone = (JSONObject) response.get(String.valueOf(i));
String acc_name = phone.getString("auto_dealer_id");
String acc_price = phone.getString("accessory_price");
jsonResponse = "";
jsonResponse += "dealer_name: " + name + "\n\n";
jsonResponse += "dealer_phone: " + phone_no + "\n\n";
jsonResponse += "dealer_add: " + add + "\n\n";
jsonResponse += "acc_name: " + acc_name + "\n\n";
jsonResponse += "acc_price: " + acc_price + "\n\n";
}
txt.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(Activity3.this).add(jsonObjReq);
}
This is my JSON data:-
{
"auto_dealer_id": "1",
"dealer_name": "RAJ MOTORS",
"phone_no": "9004296356",
"address": "THANE WEST 40002",
"0": {
"auto_dealer_accessory_id": "1",
"auto_dealer_id": "1",
"accessory_name": "CAR OILING",
"accessory_price": "40"
},
"1": {
"auto_dealer_accessory_id": "2",
"auto_dealer_id": "1",
"accessory_name": "CAR WASHING",
"accessory_price": "40"
},
"2": {
"auto_dealer_gallery_id": "1",
"auto_dealer_id": "1",
"image": "1.jog",
"status": "1",
"sort": "1",
"added_date": "0000-00-00 00:00:00"
}
}
try this code:
try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString);
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("key Items", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
but it is better approach to convert you JsonObject "1","2"... to JsonArray
Since you want to get json object inside json object,
here you can get
JSONObject number = response.getJSONObject("1");
number.getString("auto_dealer_accessory_id")
and so on.
But there are some better approaches as well. Use Gson and also improve your data structure coming from server. using an array is better option and don't forget to check if the object or string exists before you try to get a value. you can use
jsonObject.has("key")
Try this:
ArrayList acc_name = new ArrayList();
...
...
try
{
JSONObject obj=new JSONObject(responseString);
String name = obj.getString("dealer_name");
String phone_no = obj.getString("phone_no");
String add = obj.getString("address");
Iterator<String> keys = obj.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONObject innerJObject = obj.getJSONObject(key);
Iterator<String> inKeys= innerJObject .keys();
while( inKeys.hasNext() )
{
String inKeys= keys.next();
acc_name.Add(innerJObject .getString(inKeys);
..
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }