Android org.json.jsonarray cannot be converted to jsonobject error - java

I'm new in JSON, but I try to use all answers and didn't work. Help please, what I doing wrong.
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
editText.setText(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray resultArray = jsonObject.getJSONArray("query");
addresses = new ArrayList<String>();
for (int i = 0; i<resultArray.length(); i++){
addresses.add(resultArray.getJSONObject(i).getString("Name"));
Log.d("DTA",resultArray.getJSONObject(i).getString("Name"));
}
refreshAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
It's my JSON for parsing.
{
"query":{
"count":2,
"created":"2016-10-04T19:50:08Z",
"lang":"ru",
"results":{
"rate":[
{
"id":"USDRUB",
"Name":"USD/RUB",
"Rate":"62.8240",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"62.8416",
"Bid":"62.8240"
},
{
"id":"EURRUB",
"Name":"EUR/RUB",
"Rate":"70.3460",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"70.3740",
"Bid":"70.3460"
}
]
}
}
}

That's because query is not an array, it is an object. I guess you want to get the objects from rate, this is how to do it:
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject resultsObject = jsonObject.getJSONObject("results");
JSONArray resultArray = resultsObject.getJSONArray("rate");
... etc... now iterate

Related

JSONArray java.lang.String cannot be converted to JSONObject

I'm using JSONObject to parse the JSON file and get its contents. Everything goes fine but tags aren't showing in the RecyclerView.
Here's the code :
private void direct_url(){
v_title = findViewById(R.id.vid_title);
String url = kw_url_holder.getText().toString();
String server_tag_url = "https://server.com/json.json";
StringRequest request = new StringRequest(Request.Method.GET, server_tag_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
String title,views,likes,dislikes,publishedon,duration;
JSONObject object=new JSONObject(response);
title = object.getString("title");
v_title.setText(title);
JSONArray tagsJsonArray = object.getJSONArray("tags");
for(int i=0; i<tagsJsonArray.length();i++){
try {
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
}catch (JSONException e){
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
url_queue = Volley.newRequestQueue(tags.this);
url_queue.add(request);
}
The JSON:
{
"title": "The Title",
"tags": ["tag1", "tag2"]
}
An error in the logs:
Error: java.lang.String cannot be converted to JSONObject
The problem is inside your for loop in:
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
It should be
String tag;
tag = tagsJsonArray.getString(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tag);
url_result.add(tagUrlResultsModel);
Using getString() instead of getJSONObject() as the content of that JSONArray is just strings.
That's why you are getting in that catch:
Error: java.lang.String cannot be converted to JSONObject

How to parse a JSON string to ListView?

So I am beginning programming Java Android and I'm trying to parse a JSON string that I created. So, I want to parse it to a ListView and I need people to help me.
My experimental JSON file:
[
{
"HoTen":" Nguy\u1ec5n V\u0103n A",
"NamSinh":1999,
"DiaChi":"H\u00e0 N\u1ed9i"
},
{+},
{+},
{+},
{+},
{+},
{+},
{+},
{+}
]
My code but it not working:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
JSONObject jsonObject = new JSONObject(s);
for (int i =0;i<=jsonObject.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope this will help you
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
ArrayList<String> mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = String.format("HoTen: %s, NamSinh: %s, DiaChi: %s",
HoTen, NamSinh, DiaChi);
mangLV.add(result);
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
It doesn't seem like you're using your JSONObject jsonObject = new JSONObject(s);. Your for should be for(int i = 0; i<=jsonArray.length();i++), thus making your jsonObject obsolete. Also, you're passing your adapter an empty list! You never add anything to your mangLV list.
Try out this code:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = "HoTen " + HoTen + " | NamSinh " + NamSinh + " | DiaChi " + DiaChi;
mangLV.add(result); //After fetching the values, add the objects to your list
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
This should add to your ListView objects that look like this:
HoTen Nguy\u1ec5n V\u0103n A | NamSinh 1999 | DiaChi H\u00e0 N\u1ed9i

Extract a string from a JSONArray

I'm trying to build a Quiz game for fun but I'm struggling to figure out how to pull the string I want from a JSONArray in Android Studio
I'm getting the Log of the "JSON" and "results" come up in Logcat but I can't seem to work out how to set my mQuestion variable to the relevant string.
The JSON
{
"response_code":0,
"results":[{
"category":"General Knowledge",
"type":"multiple",
"difficulty":"medium",
"question":"According to the BBPA, what is the most common pub name in the UK?",
"correct_answer":"Red Lion",
"incorrect_answers": [
"Royal Oak",
"White Hart",
"King's Head"
]
}]
}
My code
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
String results = jsonObject.getString("results");
Log.i("results", results);
JSONArray arr = new JSONArray(results);
for (int i = 0; i < arr.length(); i++) {
mQuestion = arr.getJSONObject(3).getString("question");
Log.i("Question", mQuestion);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I get in the Logcat is W/System.err: at ...MainActivity$getQuestion.onPostExecute(MainActivity.java:67)
67 is the line containing "mQuestion = arr.getJSONObject(3).getString("question");"
You need to use i you declare in loop:
mQuestion = arr.getJSONObject(i).getString("question");
You are parsing JsonObject and JsonArray wrongly.
use this code:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = results.getJSONObject(0);
Log.i("results", results.toString());
String mQuestion = jsonObject1.getString("question");
Log.i("Question", mQuestion);
} catch (Exception e) {
e.printStackTrace();
}
}

Handle array data from server android

in my application data coming from a server in the form of an array,
i cant handle the data i will share my code please help me.
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
s_key = jsonObject.getString("initKey");
s_iv = jsonObject.getString("initIv");
sec_url = jsonObject.getString("url");
s_init_hash = jsonObject.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
There is no JSONArray
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject .getJSONObject(i);
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
You Response is JSONObject not in JSONArray check it
FYI
{ } brackets means JSONObject
[ ] brackets means JSONArray
Parse your json like this
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
} catch (JSONException e) {
e.printStackTrace();
}
}
data Is not Json Array cause it start with {} it`s Json Object
Json Array start with []
So you need To use
SONObject jsonObjectData = jsonObject .getJSONObject(i);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
response
{
"status": "success",
"data": {
"initKey": "abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
Code
try {
JSONObject outerJsonObject=new JSONObject(response);
String status=outerJsonObject.getString("status");
if(status.equals("success"))
{
JSONObject innerJsonObjectData=outerJsonObject.getJSONObject("data");
String initKey =innerJsonObjectData.getString("initKey");
String initHash =innerJsonObjectData.getString("initHash");
String initIv =innerJsonObjectData.getString("initIv");
String versionNo =innerJsonObjectData.getString("versionNo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Comments
/*
{
//outerJsonObject
"status":"success",
"data": // innerJsonObjectData
{
"initKey":"abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
*/
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example:
[{"name":"item 1"},{"name": "item2} ]
On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example:
{"name": "item1", "description":"a JSON object"}
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject data = jsonObject. getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}

Json parsing not working properly using volley

I am using volley for parsing. This are the parameters i am passing as post request.
{
"typeName": "MANUFACTURER",
"typeId": 22,
"tempId": 308,
"sortBy": "productname",
"sortOrder": "desc",
"filter":[
{
"filterId":101,
"typeName":"CAT_ID",
"filterId":102,
"typeName":"CAT_ID"
}
]
}
Now the issue is that if I am adding tempId then I am not getting response. but if i remove tempId I am getting proper response. I check my webservice in postman and other tools. There is no issue with Webservice . Can any one help me to solve this issue? There are no any crash log.
public void Productlistcall()
{
showpDialog();
/* Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");*/
Map<String, String> jsonParams = new HashMap<String, String>();
/* object.put("typeName","MANUFACTURER");
object.put("typeId","22");
object.put("tempId","308");
object.put("sortBy","productname");
object.put("sortOrder","desc");*/
if(filter_items!=null)
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
JSONArray array=new JSONArray();
JSONObject obj=new JSONObject();
String filtersepid = null;
System.out.println("FILTER LIST DATA IS NOT NULL");
array.put(obj);
jsonParams.put("filter",obj.toString());
for(int i=0;i<filter_items.size();i++)
{
filtersepid=filter_items.get(i);
System.out.println("filtersepid"+filtersepid);
try {
obj.put("filterId",filter_items.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
try {
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
System.out.println("FILTER LIST DATA IS NULL");
}
System.out.println("DRAWER PARAMS" + jsonParams);
JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("response Productlist-->> " + response.toString());
productlist = new ArrayList<ProductListModel>();
ch_list = new ArrayList<String>();
color_list=new ArrayList<String>();
try {
JSONObject drawerdatas = (JSONObject) response.getJSONObject("Data");
JSONArray products=drawerdatas.getJSONArray("products");
JSONArray filtersdata=drawerdatas.getJSONArray("filtersList");
JSONArray sortingdata=drawerdatas.getJSONArray("sortingList");
String headerText=drawerdatas.getString("headerText");
String productCount=drawerdatas.getString("productCount");
productlist = new ArrayList<ProductListModel>();
for (int j = 0; j < products.length(); j++) {
JSONObject jo = products.getJSONObject(j);
ProductListModel ch = new ProductListModel();
ch.setProduct_Id(jo.getString("productId"));
ch.setProduct_Name(jo.getString("productName"));
ch.setProduct_Img(jo.getString("productImage"));
ch.setProduct_Price(jo.getString("productSP"));
ch.setProduct_RatingImgPath(jo.getString("productRatingImage"));
ch.setProduct_pRating(jo.getString("productRatingCount"));
/* if(jo.getString("productOfferText").equals("null"))
{
ch_list.add(" ");
System.out.println("text is null");
}
else
{
JSONArray txtdetail=jo.getJSONArray("productOfferText");
System.out.println("txtdetailarray"+txtdetail);
StringBuilder sb = new StringBuilder();
for(int k=0;k<txtdetail.length();k++)
{
JSONObject jdetail=txtdetail.getJSONObject(k);
disptext=jdetail.getString("displayText");
dispclr=jdetail.getString("displayColor");
//ch_list.add(disptext);
color_list.add(dispclr);
// sb.append(disptext);
System.out.println("clr" + color_list.get(k).toString());
colors=color_list.get(k);
String string = colors;
String[] parts = string.split("\\*");
int part1 = Integer.parseInt(parts[0]);
int part2 = Integer.parseInt(parts[1]);
int part3 = Integer.parseInt(parts[2]);
hex = String.format("#%02X%02X%02X", part1, part2, part3);
sb.append(addColor(disptext.trim(), hex));
System.out.println("hexa"+hex);
}
detailtext=sb.toString();
ch_list.add(detailtext);
System.out.println("Output: " + sb.toString().replaceAll("\\\\n", "\n"));
}
*/
productlist.add(ch);
}
filterlist = new ArrayList<ModelUser>();
for(int c=0;c<filtersdata.length();c++)
{
JSONObject jo = filtersdata.getJSONObject(c);
JSONArray filters=jo.getJSONArray("filters");
String groupName=jo.getString("groupName");
String typeName=jo.getString("typeName");
for(int g=0;g<filters.length();g++)
{
JSONObject jos = filters.getJSONObject(g);
ModelUser flm = new ModelUser();
flm.setId(Integer.parseInt(jos.getString("filterId")));
flm.setUserName(jos.getString("filterName"));
filterlist.add(flm);
}
}
sortlist=new ArrayList<SortingListModel>();
for(int d=0;d<sortingdata.length();d++)
{
JSONObject jo = sortingdata.getJSONObject(d);
SortingListModel scm = new SortingListModel();
scm.setSort_text(jo.getString("text"));
scm.setSort_value(jo.getString("value"));
sortlist.add(scm);
}
rvAdapter = new RecyclerViewAdapter(getActivity(),productlist);
recyclerView.setAdapter(rvAdapter);
pronames.setText(headerText);
if(productlist.size() < 2)
{
procounts.setText(String.valueOf(productlist.size() + " Product"));
}
else
{
procounts.setText(String.valueOf(productlist.size() + " Products"));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle Error
hidepDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("API_Version","1.0");
headers.put("deviceName","ANDROID");
return headers;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
}
You are using this
jsonParams.put("tempId","308");
Try this
jsonParams.put("cityId","308");
Rearrange and use below code in the if else condition. You are not generating json in right order
if(filter_items!=null)
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
JSONArray array=new JSONArray();
String filtersepid = null;
System.out.println("FILTER LIST DATA IS NOT NULL");
for(int i=0;i<filter_items.size();i++)
{
JSONObject obj=new JSONObject();
filtersepid=filter_items.get(i);
System.out.println("filtersepid"+filtersepid);
try {
obj.put("filterId",filter_items.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
try {
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
array.put(obj);
}
jsonParams.put("filter",array);
}
else
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
System.out.println("FILTER LIST DATA IS NULL");
}
I solved it with the use of
compile 'com.android.volley:volley:1.0.0'
I was using this one
compile 'com.mcxiaoke.volley:library:1.0.19'

Categories

Resources