Json Parse android - 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();

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

just only one list on my listview

I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)

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

Error parsing JSON in my Android app?

I have string json like this :
{
"listResult": {
"items": [
{
"id": "629047db-66d9-4986-ba3f-c75554198138",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/629047db-66d9-4986-ba3f-c75554198138/8cb69c17-0fdb-454c-bfb5-a5b9001a9d59.jpg"
},
{
"id": "fa872dc8-d2b3-4815-92ef-d90e903bc3d8",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/fa872dc8-d2b3-4815-92ef-d90e903bc3d8/c510c24f-5bfd-4a64-8851-a5b90017a38d.jpg"
}
],
"totalItems": 34,
"pageSize": 5,
"pageNumber": 1,
"totalPages": 7,
"searchTerm": null
}
}
I Try Parsing with code :
try {
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
int jumlah_list_data = items_obj.length();
if (jumlah_list_data > 0) {
for (int i = 0; i < jumlah_list_data; i++) {
JSONObject obj = items_obj.getJSONObject(i);
String id = obj.getString(Variabel.id);
String thumbnail = obj.getString(Variabel.thumbnail);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
But I getting Error :
org.json.JSONException: No value for items
So how to solve it ? sorry for my English
Instead of:
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
you should have:
JSONObject json = new JSONObject(response);
JSONObject listResult = json.getJSONObject(Variabel.listResult);
JSONArray items_obj = listResult.getJSONArray(Variabel.items);
Accordingly to the json you posted, items is direct child of listResult, so you have to use the JSONObject with key listResult to retrieve it. Change
JSONArray items_obj = json.getJSONArray(Variabel.items);
with
JSONArray items_obj = listResult.getJSONArray(Variabel.items);

How to parse specific JSON data in Android?

This is my JSON data from a URL:
[
{ "title" : "65th Issue", "author": "అశోక్"},
{ "title" : "64th Issue", "author": "రాము" },
{ "title" : "63rd Issue", "author": "శ్రీను" }
]
It is looking like a JSONArray but it does not have its name (Array name) to access. Could anyone tell me how can I parse this JSON data in android?
Parsing Code
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char [] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
try{
JSONArray jArray = new JSONArray(responseData);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
} catch (JSONException e) {
Log.v(TAG, "JSON EXCEPTION");
}
String jsonString = ...; //This contains the above mentioned String.
For JSON String, [] denotes an array, an {} denotes an object. In your case, the string starts with a [] thats means its an array, so we first get the JSONArray.
JSONArray jArray = new JSONArray(jsonString);
Now, if you see, the array has multiple strings beginning and ending with {}, that means that the array has multiple objects. So we run a loop over the array length to extract each object and then the key - value from the object.
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
So, the complete code will be something like this :
String jsonString = ...; //This contains the above mentioned String.
JSONArray jArray = new JSONArray(jsonString);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
Edit 2 :
String jsonString = "[\r\n { \"title\" : \"65th Issue\", \"author\": \"\u0C05\u0C36\u0C4B\u0C15\u0C4D\"},\r\n { \"title\" : \"64th Issue\", \"author\": \"\u0C30\u0C3E\u0C2E\u0C41\" },\r\n { \"title\" : \"63rd Issue\", \"author\": \"\u0C36\u0C4D\u0C30\u0C40\u0C28\u0C41\" }\r\n]";
try {
JSONArray jArray = new JSONArray(jsonString);
for (int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
Log.d(LOGTAG, title);
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources