This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Issue:
I'm getting data from web-services in JSON format.I am trying to parse "quote" an "Author" but,i am unable to do it.
Here is the data:
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "You are very powerful, provided you know how powerful you are.",
"author": "Yogi Bhajan",
"category": "inspire",
"date": "2018-02-15",
"title": "Inspiring Quote of the day"
}
],
"copyright": "2017-19 theysaidso.com"
}
}
My Java code is :
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
I'm certain that logic for parsing in Java class is incorrect.
Which logic should I use to correct this?
First, you have to get the JSONObject contents before extracting the array quotes.
try {
JSONObject obj = response.getJSONObject("contents"); //first get the JSONObject contents
JSONArray jsonArray = obj.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
You missed contents JSONObject.
Copy past below code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject contentsObject=response.getJSONObject("contents");
JSONArray jsonArray = contentsObject.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject contents =
response.getJsonObject("contents");
try {
JSONArray quotes = contents.getJSONArray("quotes");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < quotes.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Try this...
Related
here_is_json_api
And my code
ArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
// JSONObject jsonObject = (JSONObject) response.get(i);
jsonObject = response.getJSONObject(i);
JSONObject jsonObjectt = jsonObject.getJSONObject("search_result");
Users users = new Users();
users.setId(jsonObjectt.getString("id"));
users.setUser(jsonObjectt.getString("User"));
users.setName(jsonObjectt.getString("name"));
users.setWho(jsonObjectt.getString("who"));
users.setImage(jsonObjectt.getString("image"));
userlist.add(users);
}
catch (JSONException e) {
e.printStackTrace();
}
}
setRvadapter(userlist);
i can not fetch any data from api , Its says JSONObject cannot be converted to JSONArray in android
you are using JsonArray as a response and your web service return a jsonobject
new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray teachers = response.getJSONArray("search_result");
for(int i = 0; i < teachers.length() ; i++) {
// do what ever you want with
Teacher teacher = new Teacher();
// here is how to get name
teacher.setId(teachers.getJSONObject(i).getString("name"));
// do the rest like this.
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);
This is my code and I am having error to parse data from object, what changes can be done so as to parse data...
aQuery.ajax(fetch_url, JSONObject.class, new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject obj, AjaxStatus status){
super.callback(url, obj, status);
Log.i("response", url + "response:" + obj);
ArrayList<UserInfo> list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("org_list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
UserInfo info = new UserInfo();
info.id = object.getString("Id");
info.servicename = object.getString("name");
info.amount = object.getString("amount");
list.add(info);
});
}
And this is my JSON data format
{
"org_list": [
{
"Id": "1",
"name": "CBC-Test",
"amount": "200"
}
]
}
When i edit from the below code and now i am facing null response value. I have also attached my logcat image file for further more details about my problem:Click here
Click here for further more details in my code
Logcat View1
Logcat View2
Edit your code as below,
aQuery.ajax(fetch_url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject obj, AjaxStatus status) {
super.callback(url, obj, status);
Log.i("response", url + "response:" + obj);
ArrayList<UserInfo> list = new ArrayList<>();
try {
JSONArray jsonArray = obj.getJSONArray("org_list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
UserInfo info = new UserInfo();
info.id = object.getString("Id");
info.servicename = object.getString("name");
info.amount = object.getString("amount");
list.add(info);
}
} catch (Exception e){
e.printStackTrace();
}
}
});
No need to re-create object of JsonObject. Just use that from response.
Finally I searched my self and found a solution. But it is without using AQuery and it is by using RequestQueue...
txtview = findViewById(R.id.showdata);
Button buttonParse = findViewById(R.id.showbtn);
requestQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
jsonParse();
}
});
}
public void jsonParse(){
String fetchurl = "http://use your url here.com/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("org_list");
for (int i=0; i < jsonArray.length(); i++){
JSONObject patient = jsonArray.getJSONObject(i);
String firstName = patient.getString("orga_organame");
txtview.append(firstName+","+"\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
i have a problem with my code and other post cannot helped me that's why i post here.
I'm getting some json from my php like
{
"lesMots":{
"1":{
"id":"4",
"wordFrench":"bite",
"wordEnglish":"dick"
},
"2":{
"id":"7",
"wordFrench":"pute",
"wordEnglish":"whore"
},
"3":{
"id":"2",
"wordFrench":"ordinateur",
"wordEnglish":"computer"
},
"4":{
"id":"1",
"wordFrench":"bonjour",
"wordEnglish":"hello"
},
"5":{
"id":"3",
"wordFrench":"monde",
"wordEnglish":"world"
}
}
}
Here is my Volley Request, i know i must use JSONObject for my JSONArray, but when i change it, the second JSONObject word ask me string and not int !
i'm trying to get 5 random french word and english word
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
Thank for your help, i'm blocked on this problem and i'm kind of new in this.
If you need something more tell me
Try this, it will loop through the object based on the keys:
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
if (lesMots.get(key) instanceof JSONObject ) {
JSONObject obj = (JSONObject) lesMots.get(key);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
You have to change jsonarray to jsonobject.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonArray = response.getJSONObject("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
the issue is that you have an obaject not an array solution can be this:
(where you response is the same you receive from the callback)
for example to mock this you can do:
String responseJson = "{\"lesMots\":{\"1\":{\"id\":\"4\",\"wordFrench\":\"bite\"," +
"\"wordEnglish\":\"dick\"},\"2\":{\"id\":\"7\",\"wordFrench\":\"pute\"," +
"\"wordEnglish\":\"whore\"},\"3\":{\"id\":\"2\"," +
"\"wordFrench\":\"ordinateur\",\"wordEnglish\":\"computer\"}," +
"\"4\":{\"id\":\"1\",\"wordFrench\":\"bonjour\",\"wordEnglish\":\"hello\"}," +
"\"5\":{\"id\":\"3\",\"wordFrench\":\"monde\",\"wordEnglish\":\"world\"}}}";
JSONObject response = new JSONObject(responseJson);
then in your callback
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMotsObject = response.getJSONObject("lesMots");
JSONArray jsonArray = lesMotsObject.toJSONArray(lesMotsObject.names());
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
...
I am posting some data into the database using Volley and I get the following jsonarray response.
[
{
"nickname":"panikos",
"username":"panikos#gmail.com",
"user_type":"LEADER",
"latest_steps":"0"
}
]
This is a sample of my code that unfortunately doesn't log out or debug the variable of "nickname" object:(.
final JsonArrayRequest jsonObjReq1 = new
JsonArrayRequest(AppConfig.URL_GET_TEAM, jsonObject,
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
Any ideas? Am I missing something?
Thanks.
I the problem might be - you are already getting response as a JSONArray.
So, you can Call
JSONObject jresponse = response.getJSONObject(0);
and if you have more than 1 object in response, then
for(int i = 0; i < response.length(); i++){
JSONObject jresponse = response.getJSONObject(i);
String nickname = jresponse.getString("nickname");
Log.d("nickname", nickname);
}
Remove this :
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
and add :
try {
JSONObject jresponse = response.getJSONObject(0);
String nickname = jresponse.getString("nickname");
Log.d("nickname",nickname);
}catch (JSONException e) {
e.printStackTrace();
}
The Code looks good, however i think you might be missing a call to add jsonObjReq1 in the request queue. I would suggest to use Singleton Pattern.
Fixed!!!
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
Log.d("JsonArray",response.toString());
for(int i=0;i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String nickname = jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
There was no need to create a new JSONArray. It was created inside the onResponse() method. The next project I am assigned to do is going to have more complicate webservices.omg!!!