Get Specific Value from JSONArray - android

i got an jsonarray:
[
{
"ean": "8020079127",
"nr": "100",
"name": "Name1"
},
{
"ean": "8026180222",
"nr": "4",
"name": "Name2"
},
{
"ean": "6577426092",
"nr": "1",
"name": "Name3"
}
]
I need the value from "nr" depending on the "ean" means:
I got the ean 8026180222 (as string) and need the value from the "nr" (here "4"). how I can get it?
its possible without iterate over the whole array?
thank you

Try this:
// Use a map to store ean,nr (as key/value)
HashMap<String, String> jsonMap = new HashMap<String, String>();
// Load the data from json
JSONArray jsonArray= new JSONArray(yourJsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String ean = jsonObj.getString("ean");
String nr = jsonObj.getString("nr");
String name = jsonObj.getString("name");
jsonMap.put(ean, nr); // here you put ean as key and nr as value
}
To retrieve an nr value of a specific ean just call: jsonMap.get(yourEAN);
Example: String nr = jsonMap.get("8026180222");

List<NameValuePair> params = new ArrayList<NameValuePair>();
JsonObject json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("Tag", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray jsnObj;
try {
jsnObj = json
.getJSONArray(TAG_ARRAY);
JSONObject obj = jsnObj
.getJSONObject(1);
String nr = obj.getString(TAG_NR);
}
Catch(Exception ex){}
}
}
If you want array you can use loops in json array.....................Hope it will help
Just define
private static final String TAG_SUCCESS = "success";
private static final String TAG_NR = "nr";
private static final String TAG_ARRAY = "array_name";

Related

Can't figure out this JSON parsing error

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()
}

How to parse a JSON string in Android?

The following JSON string comes to me after a request. Whatever I try, I can not parse the data.
[{
"_id": {
"$oid": "5909846cbd966f2d371bc624"
},
"member_id": "NTkwOTEyNzdiZDk2NmYyZDM3MTkyY2M1",
"sensor_name": "Temprature",
"value": "27.28",
"date": "2017-05-03 10:19:07"
}]
Try using following code :
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.get(0);
JSONObject _id = jsonObject.getJSONObject("_id");
String old = _id.getString("$oid");
String member_id = jsonObject.getString("member_id");
String sensor_name = jsonObject.getString("sensor_name");
String value = jsonObject.getString("value");
String date = jsonObject.getString("date");
}catch(JSONException e){
}

Json Parsing object inside Object getting error

-- I know parsing, i have successfully parsed below data, but when web-service is upgraded i need to parse object inside object.
- I tried many example but getting error.
Code for Parsing :
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "Message";
private final String KEY_MSG1 = "Message";
// private final String KEY_AddressList = "addressList";
private final String KEY_USERINFO = "user_info";
ArrayList<HashMap<String, String>> arraylist;
private final String KEY_DATA = "data";
private final String KEY_USERDATA = "userdata";
public ArrayList<HashMap<String, String>> getList(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// JSONObject job = obj.getJSONObject("User");
Log.d("obj", obj.toString());
String user_id = obj.getString(Constants.Params.ID);
String createdate = obj.getStringAndyConstants.Params.CREATEDDATE);
String postImage = obj.getString(Constants.Params.IMAGE);
map.put(AndyConstants.Params.ID, user_id);
map.put(AndyConstants.Params.CREATEDDATE, createdate);
map.put(AndyConstants.Params.IMAGE, postImage);
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
for (int j = 0; j < jsonArrayUser.length(); j++) {
HashMap<String, String> mapUser = new HashMap<String, String>();
JSONObject businessObject = jsonArrayUser.getJSONObject(j);
Log.d("obj", businessObject.toString());
}
Log.d("map", map.toString());
arraylist.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return arraylist;
}
Error Log :
org.json.JSONException: No value for data
E/array: []
E/adapter: []
Json :
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}
You dont need this line
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
and change
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
to
JSONObject userData = obj.getJSONObject("userdata");
String firstName = userData.getString("first_name");
String lastName = userData.getString("last_name");
As you can see from the JSON
"data":
[{"user_id":"46",
"image":"",
"createdate":"2016-05-11 06:05:12",
"userdata":{"first_name
data is having the object [ which denotes an Array while userData shows a { which is a JSONObject
I notice that your JSON has some errors. is this the complete Json response?
Because JSON response should be something like this:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}]
}
You will notice that there is no close for [ after userdata in your Json.

Json Parse android

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();

Remove JSONobject from JSONarray in Android

I have Dynamic JSON String i want to remove the last JSON object from the JSONARRAY in android. here is my dynamic JSON String in android. My json string is
("{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
{
"findAllUsersResponse": [
{
"id": "kicJw2whXyuGjbNo936L",
"name": "Fghhjj",
"udid": "2AA120E3-7478-4AD4-9C68-9C0920669B84"
},
{
"id": "NEF45TWNI6-Uc_r7938R",
"name": "ssss",
"udid": "1DD083C2-7F1D-4BB3-9AB9-691A5FD251CC"
},
{
"id": "xuXY7Ah2-O-jL4Zk939D",
"name": "Test",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
},
{
"id": "w1FnBz8B9ciWUzBk939k",
"name": "Aditi",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
}
]
}
If your String is not going to change and you only want last object to be deleted use substring and create new string.
String finduserjson= "{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
String t = finduserjson.substring(finduserjson.indexOf("{"), finduserjson.lastIndexOf(",{"));
String j = "]}";
finduserjson = t+j;
Cheers
Was facing a similar problem. There are no methods in the JSONarray object to get what you want. You could make a function to remove it. Saw this solution somewhere.
public static JSONArray remove(final int index, final JSONArray from) {
final List<JSONObject> objs = getList(from);
objs.remove(index);
final JSONArray jarray = new JSONArray();
for (final JSONObject obj : objs) {
jarray.put(obj);
}
return jarray;
}
public static List<JSONObject> getList(final JSONArray jarray) {
final int len = jarray.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = jarray.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
Cheers!
If you are using JSON rather than GSON or JACKSON, then you cannot call .remove() method because you would not find it there.
Best thing you can do is, re-create a new JSONArray and add required JSONObjects in it.

Categories

Resources