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
Related
I want parse JSON response.I am unable to parse response.It shows org.json.JSONException: No value for String Response this error.
Here is my code ` public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
JSONObject jsonObject = response.getJSONObject("String Response"+response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}`
I guess you use Volley JsonObjectRequest, so you need to convert the response to a String and parse it to a JSONObject, like this:
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONObject jsonObject = new JSONObject(response.toString());
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}, error -> {}
);
try {
JSONObject jsonObject = response.getJSONObject(response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
before you will do parsing , you will check all value receice by API exp :- responseCode, responseText, personName ( https://jsonlint.com/ ) , if all value you recived , check its in correct format , after that you will parse the data
you also use this , its will handle the JsonException
jsonObject.optString("responseText");
Solved this problem with this code
public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
// JSONObject jsonObject = response.getJSONObject(response.toString());
strcode = response.getString("responseCode");
strtext = response.getString("responseText");
strname = response.getString("personName");
Log.i("TAGParser","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + 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 am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:
[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables
After sometime trying and trying I found a way to
String finalJson = buffer.toString();
try {
JSONArray parentArray = new JSONArray(finalJson);
int count = 0;
int[] id = new int[parentArray.length()];
String[] title = new String[parentArray.length()];
StringBuffer finalBufferedData = new StringBuffer();
while (count < parentArray.length())
{
JSONObject finalObject = parentArray.getJSONObject(count);
id[count] = finalObject.getInt("id");
title[count] = finalObject.getString("title");
finalBufferedData.append(id[count] + " - " + title[count] + "\n");
count++;
}
return finalBufferedData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)
Here is the working code:
public void parseJson() {
// Response from API call
String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
"{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";
try {
JSONArray jsonArray = new JSONArray(response);
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = null, title = null;
// Id
if (jsonObject.has("id") && !jsonObject.isNull("id")) {
id = jsonObject.getString("id");
}
// Title
if (jsonObject.has("title") && !jsonObject.isNull("title")) {
title = jsonObject.getString("title");
}
Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
+ "\nTitle: " + title);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Id: 1
Title: 12 May to 30 Jun
D/SUCCESS: JSON Object:
Id: 2
Title: 3 Jun to 20 Jun
protected void onPostExecute(String result)
{
//result parameter should be final so that it can be used in cross thread operation
super.onPostExecute(result);
if (result != null) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String Brand = object.getString("UserName");
HashMap<String, String> itemList = new HashMap<String, String>();
itemList.put("UserName", Brand);
BrandList.add(itemList);
}
**adapter = new SimpleAdapter(Main2Activity.this, BrandList, R.layout.list, new String[]{"UserName"}, new int[]{R.id.txtTitel});
((AdapterView<ListAdapter>) listView).setAdapter(adapter);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Toast.makeText(Main2Activity.this, "Could not get any data.", Toast.LENGTH_LONG).show();
}
}
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());
}