Currently I'm trying to display JSON data (hosted on a Webserver) in a ListView in Android. The App correctly receives the data but is unable to process it further to display it in said ListView.
The error is as follows:
JSON parsing error: Value ... of type org.json.JSONArray cannot be converted to JSONObject
The JSON data I'm trying to parse looks like the following:
[{"idBuch":1,"autor":"Erich Maria Remarque","name":"Im Westen nichts Neues","preis":20,"buchtyp":{"idBuchtyp":3,"typenamen":"Geschichte"}}]
The code that processes the received JSON-String:
try{
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray books = jsonObject.getJSONArray("book");
for(int i = 0; i < books.length(); i++){
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap<String, String> book = new HashMap<>();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
} }catch(final JSONException e)
I am aware of the fact that there are a lot of similar questions on this site but I still had no success regarding this issue. Thank you in advance.
The JSON that you provided only contains an array.
[
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
However, your code expects the root to be an object with field book.
{
"book": [
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
}
In this case, try replacing the line:
JSONObject jsonObject = new JSONObject(jsonStr);
with
JSONArray books = new JSONArray(jsonStr);
and proceed as normal. Your end result should look like:
try {
JSONArray books = new JSONArray(jsonStr);
for (int i = 0; i < books.length(); i++) {
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap < String, String > book = new HashMap < > ();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
}
} catch (final JSONException e) {
e.printStackTrace()
}
Related
I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray
I am trying to parse a key from JSONArray which is:
{
"server": [
{
"id": "1",
"name": "Steve",
"email": "test#gmail.com",
"phone": "1001001000"
}
]
}
Since, the key, which is id, name, email, and phone can be dynamically changed, we have to parse the result without teaching the key value. That is, the system has to parse both the key and the value. So I thought getting an array and using the iterator.hasNext() will solve the problem.
JSONObject jsonObject = new JSONObject(stringBuilder.toString().trim());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while (iterator.hasNext()){
hashMap.put(iterator.next().toString(), json_object.getString(iterator.next().toString()));
}
}
It doesn't work properly whether changing the iterator to jsonObject.keys() or json_object.keys(), but only parses the key value of "id", and can't parse the name, email, phone.
This is how I get the JSON file:
$result = mysqli_query($conn, $sql);
$data = array();
if ($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('id'=>$row[1],
'name'=>$row[2],
'email'=>$row[3],
'phone'=>$row[4]
));
}
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("server"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
Try this
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray jsonArray = jsonObject.getJSONArray("server");
for (int current = 0; current < jsonArray.length(); current++){
JSONObject json_object = jsonArray.getJSONObject(current);
Iterator iterator = json_object.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
if ( json_object.get(key) instanceof String ) {
hashMap.put(key, json_object.getString(key));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("OUTPUT", Arrays.asList(hashMap).toString());
OUTPUT
The is my JSON string .
{
"server_response":
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
}
I think there would be a '[' after "server_response" , but not sure .
I am trying to retrieve the data but the code is not working .
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count=0 ;
String stoppage,busno;
while(count<1)
{
JSONArray JA = jsonArray.getJSONArray(0);
JSONObject JO = JA.getJSONObject(count);
stoppage = JO.getString("stoppage_name");
busno = JO.getString("bus_no");
Toast.makeText(getApplicationContext(),"Stoppage ="+ stoppage+" Bus no =" +busno, Toast.LENGTH_LONG).show();
count ++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Where I am making wrong . I am new to JSON and Android.
jsonObject = new JSONObject(json_string);
jsonServerObject = jsonObject.getJSONObject("server_response");
jsonSourceArray = jsonServerObject.getJSONArray("source_response");
jsonDestinationArray = jsonServerObject.getJSONArray("destination_response");
//Iterate your 2 arrays
server_response is not a JSONArray, it's a JSONObject. Because array have numeric key, not string.
i have already answer this type of question .. what you have to do .. use multiple for loop to getting value inside array under array.
this is srceen shots
JSONArray objJson = new JSONArray(strJSONData);
System.out.println("AppUserLogin:"+objJson);
// Parsing json
if(arrJson.length()>0)
{
for (int i = 0; i < objJson.length(); i++) {
try {
JSONObject objprod = arrJson.getJSONObject(i);
HashMap<String, String> MaplistTemp = new HashMap<String, String>();
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
JSONArray objproduct_var = new JSONArray(objprod.getString("LearningStandards"));
if ((objproduct_var.length()) > 0) {
for (int k = 0; k < objproduct_var.length(); k++) {
JSONObject objprodvar = objproduct_var
.getJSONObject(k);
MaplistTemp
.put("1",
objprodvar
.getString("1"));
MaplistTemp
.put("2",
objprodvar
.getString("2"));
MaplistTemp
.put("3",
objprodvar
.getString("3"));
MaplistTemp
.put("4",
objprodvar
.getString("4"));
}
}
// sub_categorys_details.add(sub_cat_det);
medpostList.add(MaplistTemp);// adding to final hashmap
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try this , and {} = object [] = array
try{
jsonObject = new JSONObject(json_string);
injsonObject = jsonObject.getJSONObject("server_response");
jsonArray = injsonObject.getJSONArray("source_reponse");
}catch(Exception e){}
sonArray = jsonObject.getJSONArray("server_response");
Here you are trying to access server_response as an array. It isn't an array. "server_response" is the key to the nested object:
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
See? Thats not an array, tis a JSON object with two keys, each of them have an array as value.
I'm not very familiar with android or java but in plain old javascript you could try something like:
var sourceResp = jsonObject.server_response.source_response;
or
var sourceResp = jsonObject["server_response"]["source_response"];
That will produce an array with one item in it.
I hope this can get you going.
Hi guys i got a json string like
{
"Successful": true,
"Value": "{\"MesajTipi\":1,\"Mesaj\":\"{\\\"Yeni\\\":\\\"Hayır\\\",\\\"Oid\\\":\\\"3d9b81c9-b7b3-4316-8a73-ad4d54ee02a8\\\",\\\"OzelKod\\\":\\\"\\\",\\\"Adet\\\":1,\\\"ProblemTanimi\\\":\\\"999\\\",\\\"HataTespitYeri\\\":\\\"Montajda\\\",\\\"Tekrar\\\":\\\"Evet\\\",\\\"ResmiBildirimNo\\\":\\\"\\\",\\\"Malzeme\\\":\\\"5475ffdb-0bc0-49cb-9186-429c60dbf91b\\\",\\\"HataKodu\\\":\\\"c30df623-496b-4a62-ba16-493bd435ca33\\\",\\\"Tarih\\\":\\\"2016-04-16 10:34:00\\\",\\\"KayitNo\\\":\\\"1600010.2\\\"}\"}"
}
I need to get "Oid" value from this string.
I tried to get it with
Gson gson = new Gson();
JsonParser parse = new JsonParser();
JsonObject jsonobj = (JsonObject) parse.parse(snc);
String stroid = jsonobj.get("Oid").toString();
But it gives null referance exception ? Any idea how can i get the only Oid value ?
Edit
I already tried How to parse JSON in Java but still no succes
What i tried from this page :
String pageName = jsonObj.getJSONObject("Value").getJSONObject("Mesaj").getString("Oid");
lets say this is your JSON
{
"success":"ok",
"test" : [{"id" : "1" ,"name" : "first"}]
,"RPTF":
[{"cats":[{"id" : "1" ,"name" : "first"},
{"id" : "1" ,"name" : "first"},
{"id" : "2" ,"name" : "test"} ]
,"pics" : [{"id" : "12" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" },
{"id" : "10" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" } ]
}]
}
method number one (if you want to access "success")
public String jsonOne(String json, String target) {
String result;
try {
JSONObject jo = new JSONObject(json);
result = jo.getString(target);
} catch (JSONException e) {
return "";
}
return result;
}
you can simply call this method like this
jsonOne(String json, "success");
method number two (in case you want to access "id"s inside the "test")
public String[] jsonTwo(String json, String target0, String target1) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
result = new String[ja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojo = ja.getJSONObject(i);
result[i] = jojo.getString(target1);
}
} catch (JSONException e) {
}
return result;
}
you get an array String on call :
jsonTwo(String json, "test", "id");
method number three (let's say you want to access "value"s in side "pics")
public String[] jsonThree(String json, String target0, String target1,String target2) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
JSONObject jojo=ja.getJSONObject(0);
JSONArray jaja=jojo.getJSONArray(target1);
result = new String[jaja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojojo = jaja.getJSONObject(i);
result[i] = jojojo.getString(target2);
}
} catch (JSONException e) {
toast("Wrong");
}
return result;
}
on call :
jsonThree(String json, "RPTF", "pics", "value");
you can write more methods like this and just call them .
The problem is because of extra " " in the "Value" section of JSON, so it will be treated as String not an object. The better solution is to seek the source of the JSON to see why they added extra " " and clear that but if you don't have access the source I propose the following:
Replace:
String stroid = jsonobj.get("Oid").toString();
with:
String valueString = jsonobj.getString("Value");
jsonobj = new JSONObject(valueString);
String mesagString = jsonobj.getString("Mesaj");
jsonobj = new JSONObject(mesagString);
String stroid = jsonobj.getInt("Oid").toString();
Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}