JSON parsing without array name or node in Android [duplicate] - android

This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a JSOn array without array name and I'm confused how to parse it and how to make JSONObject or JSONArray. If possible then please describe it.
My JSON Array list is:
[{
name:"Product_fill",
image:"https://something.com/product1.jpg",
title:"Laptop 1"
},
{
name:"Product_fill2",
image:"https://something.com/product2.jpg",
title:"Laptop 2"
},
and my code is :
RequestQueue queue= Volley.newRequestQueue(this);
String Url="http://msomething.com/list.php";
StringRequest request=new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONObject jsonObject=new JSONObject(response);
JSONObject main=jsonObject.getJSONObject("array");
JSONArray jsonArray=jsonObject.getJSONArray("0");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1=jsonArray.getJSONObject(i);
textView.setText(jsonObject1.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}

Try this:
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
textView.setText(jsonObject.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}

You can pass the response string to the JSONArray constructor directly and then parse the array using a loop
JSONArray jsonArray = new JSONArray(response);
Tip: I would search how to use other json libraries like Gson or Jackson as the Android built-in parser is not good.

Related

JSON Array Request Parsing error using Volley Library

I'm working on a news application with api from newsapi.org. I'm using volley library for making JSONArrayRequest and getting data. I'm trying to get my head around json array and json object to understand the parsing. Unfortunately, I'm unable to parse the response. It always calls OnErrorResponse where the response is the json data. Can someone guide me how can I parse the response?
Response:
URL to site:
https://newsapi.org/docs/endpoints/sources
Parsing:
public void jsoncall() {
JsonArrayRequest arrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject;
Log.d("OnResponse", "" + response);
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("sources");
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Toast.makeText(getActivity(), "" + jsonObject1.getString("name"), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this,anime.toString(),Toast.LENGTH_SHORT).show();
lstAnime.add(anime);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "Size of Liste " + String.valueOf(lstAnime.size()), Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), lstAnime.get(1).toString(), Toast.LENGTH_SHORT).show();
setRvadapter(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("OnErrorResponse",""+error.toString());
}
});
requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
requestQueue.add(arrayRequest);
}
dear you are receiving JSONObject include "status" and "sources". I suggest to call JsonObjectRequest
Then parse your response to get JSONArray "sources" :response.getJSONArray("sources");

Parsing an array from Flask to Android

I am trying to parse an array that I have retrieved from my flask server. The array is as follows.
"[{\"firstName\": \"Roy\", \"lastName\": \"Augustine\"}]"
I am parsing the array in Android studio using the following code.
private void loadDrives() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://142.93.216.24:5000/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
//adding the product to product list
driveList.add(new TestMl(
jsonObject.getString("firstName"),
jsonObject.getString("lastName")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
I am however getting the following error.
org.json.JSONException: Value [{"firstName": "Roy", "lastName": "Augustine"}] of type java.lang.String cannot be converted to JSONObject
The error suggests that the json is being successfully retrieved, but it cannot parse the array successfully. Could anybody suggest a suitable solution?
YOu're fetch data using wrong name.. it is lastName not lastname
Change this
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
To
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));

How to fetch json data from an array using volley Library? [duplicate]

This question already has answers here:
How do you use the Android Volley API?
(8 answers)
Closed 5 years ago.
My json Data
{"code":1200,"message":"Data Retrieved","data":[{"id":1,"name":"Vangipurapu Venkata Sai Laxman","skills":"Cricketer, Batsman","image":"https:\/\/qph.ec.quoracdn.net\/main-qimg-4f5029c4319b41270f5643d461979645-c"},{"id":2,"name":"Himesh Reshammiya","skills":"music director, singer, producer, lyricist, distributor and actor","image":"https:\/\/starsunfolded-1ygkv60km.netdna-ssl.com\/wp-content\/uploads\/2016\/01\/Himesh-Reshammiya-nasal-singing.jpg"},{"id":3,"name":"Rajkummar Rao","skills":"Indian actor","image":"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcQhShfz5g33MOXBKtLlEXo16uuxEpHFL8NYQE2lg071avavYeKr"},{"id":4,"name":"Pusarla Venkata Sindhu","skills":"badminton player","image":"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcTC0wYTxk72MNx5IADgDDMAqUz9AEyfR6UZexWNqn_fKFNZCLz-"}]}
This is my Mainactivity
MainActivity.java
JsonArrayRequest rqst = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(obj.getString("name"));
dataSet.setImage(obj.getString("image"));
dataSet.setSkills(obj.getString("skills"));
list.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
What changes Should i Made to fetch the data? I should fetch that data in to an listview.
you are expecting a JSONArray but your response is a JSON object that contains a JSON array.
modofy your request to a StringRequest
StringRequest strtRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
JSONObject obj = new JSONObject(response);
JSONArray arr=obj.getJSONArray("data");
for(int i=0;i<arr.length();i++){
JSONObject jo=arr.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(jo.getString("name"));
dataSet.setImage(jo.getString("image"));
dataSet.setSkills(jo.getString("skills"));
list.add(dataSet);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) ;

How can I parse a JSON request using Volley?

I am using the Volley Facebook library to parse the JSON object by passing the String Parameter. But it's throwing JSON exception.
[
{
"error":false,
"newsletter":[
{
"title":"IPS Informa",
"date":"2015-12-02",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello World",
"id":"4",
"post_count":"0"
},
{
"title":"IPS Informa",
"date":"2015-11-30",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello Worl Two",
"id":"1",
"post_count":"6"
}
]
}
]
And here is My Android Code to parse my JSON request:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
JSONObject first = new JSONObject(response);
String err = first.getString("error");
JSONArray second = first.getJSONArray("newsletter");
fisco_tips.clear();
// Parsing json
for (int i = 0; i < second.length(); i++) {
JSONObject obj = second.getJSONObject(i);
FisoTipsSinglton fisco_obj = new FisoTipsSinglton();
//Set Newsletter ID
fisco_obj.setFisco_id(obj.getString("id"));
//Set Title
fisco_obj.setTitle(obj.getString("title"));
//Set Posted Date
fisco_obj.setPosted_date(obj.getString("date"));
//Set Posted By
fisco_obj.setPosted_by(obj.getString("posted_by"));
//Set Image URL
fisco_obj.setThumbnailUrl(obj.getString("image"));
//Set Short Description
fisco_obj.setShort_description(obj.getString("description"));
fisco_obj.setPost_count(obj.getString("post_count"));
fisco_tips.add(fisco_obj);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Json Error", "Here is error: " + e.toString());
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("country", country);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, related_posts);
}
How can I read my JSON object using string request in Android Volley library?
The error message that you're getting:
type org.json.JSONArray cannot be converted to JSONObject
indicates that you're trying to convert a JSONArray to a JSONObject. This happens in the first line of code in your try block.
JSONObject first = new JSONObject(response);
You're passing the entire response to the JSONObject constructor, but the response is wrapped in [ ], so it's a JSONArray, not a JSONObject. Your first step should be to parse the response as a JSONArray, get the JSONObject from the first element of the array, then continue parsing.
try {
JSONArray wrapper = new JSONArray(response);
JSONObject first = (JSONObject)wrapper.get(0);
boolean err = first.getBoolean("error");
JSONArray newsletters = first.getJSONArray("newsletter");
// Parsing json
for (int i = 0; i < newsletters.length(); i++) {
JSONObject news = newsletters.getJSONObject(i);
.
.
.
}
} catch (JSONException e) {
Log.d("MainActivity.java", e.toString());
}
If there's a chance that your data source might return an empty array, you should do more error checking than I've shown here.
String err = first.getString("error");
Should be:
Boolean err = first.getBoolean("error");
Plus what Bill the Lizard said.
Instead of using Volley check OkHTTP with Retrofit. It will wrap responses automatically ;)

JSONArray response with Volley for Android

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!!!

Categories

Resources