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")
));
Related
I'm trying to parse json using volley but I cant receive the data. Assume that I received the data. I send that to the recycler view. But I'm not sure about using the JSONObject. Maybe there is a error I couldn't see it. And this is my json website "https://docs.spacexdata.com/#3d6e6f8a-a459-4265-84b1-e2b288a58537".
private void parseJson() {
String url = "https://docs.spacexdata.com/#d65a7f85-e0c7-41ce-b41d-9ad20a238d90";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i = 0; i < response.length(); i++) {
JSONObject capsuleObject = response.getJSONObject(i);
String details = capsuleObject.getString("details");
String type = capsuleObject.getString("type");
mCapsuleList.add(new Capsule("null", "null", "null", "null", 0, 0, type, details, 0));
}
mCapsuleAdapter = new CapsuleAdapter(CapsuleFragment.this.getContext(), mCapsuleList);
mRecyclerView.setAdapter(mCapsuleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
There is a lot of value in json but I just want to receive "type" and "detail". It says my request is null. So how can i parse this?
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");
I managed to show the data from a Json file with Volley in RecycleView. The line that says "photo = finalLink.getString("href");" is a link to another Json file. I don't want to show the link. I want to show the data that there are in that Json file. How do i do that?
https://psaddict.gr/wp-json <--- This is the first Json file. And there is a link to another Json file that goes to varius json file and I want to get the data from these json files for example https://psaddict.gr/wp-json/wp/v2/media
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
final JSONObject jsonObject = response.getJSONObject(i);
JSONObject mmname = jsonObject.getJSONObject("title");
JSONObject explain = jsonObject.getJSONObject("excerpt");
JSONObject mmlinks = jsonObject.getJSONObject("_links");
JSONArray lllinks = mmlinks.getJSONArray("wp:featuredmedia");
JSONObject finalLink = lllinks.getJSONObject(0);
photo = finalLink.getString("href");
Model model = new Model();
model.setTitle(mmname.getString("rendered"));
model.setReference(explain.getString("rendered"));
model.setTest(finalLink.getString("href"));
modelList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
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.
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 ;)