Parse json in Java android studio - java

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???

First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}

You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array

String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to read Json Android

i so confused ! i'm so trying to read this json but i can't :-(
here is my code :
{"status":"loged_in","token":"8e88776a14f4da4ef8e00955f83e1397","nikeName":"سعید"}
try {
postTextandGetRespons("http://gfac.ir/KatibehPayam/Service/login.php");
JSONArray messages = new JSONArray(responseString);
for ( int i=0; i<= messages.length();i++){
JSONObject c = messages.getJSONObject(i);
Status[0] = c.getString("status");
Status[1] = c.getString("token");
Status[2] = c.getString("nikeName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Your responseString contains an object not an array so use JSONObject instead of JSONArray
JSONObject message = new JSONObject(responseString);
String status = message.getString("status");
String token = message.getString("token");
String nikeName = message.getString("nikeName");

Converting array list object to jsonarray

I have arraylist that needs to be converted to json array to post in the server
the format of json should be like this:
{
p:1,
s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4]
}
Let say I have:
List<MyObject> objectList = new ArrayList<MyObject>();
MyObject myObject = new MyObject();
myObject .setA(1);
myObject .setB(2);
myObject .setA(2);
myObject .setB(3);
myObject .setA(3);
myObject .setB(4);
objectList.add(myObject);
My current code is:
for (int i = 0; i < objectList.size(); i++) {
JSONArray ar = new JSONArray();
ar.put("a:"+objectList.get(i).getA());
ar.put("b:"+objectList.get(i).getB());
jOuter.put("s",ar);
}
but this doesnt work, the current return is:
{"p":1,"s":["a:20","b:10.0"]}
Thanks.
Shouldn't it be something like this?
JSONArray ar = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject objects = new JSONObject();
objects.put("a", objectlist.get(i).getA();
objects.put("b", objectlist.get(i).getB();
ar.put(objects);
}
jOuter.put("s",ar);
Your s entry is actually a JsonArray, while your p is just a property. Here I am using Gson but you could easily apply it to whichever library you are using. So you can do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("p", 1);
JsonArray sArr = new JsonArray();
for (int i = 0; i < objectList.size(); i++)
{
JsonObject innerObj = new JsonObject();
innerObj.addProperty("a:"+objectList.get(i).getA());
innerObj.addProperty("b:"+objectList.get(i).getB());
sArr.add(innerObj);
}
jObj.addProperty("s", sArr);
The output is:
{
"p":1,
"s":[{"a":1,"b":2},{"a":3,"b":4}]
}
Your required format is invalid.
I think you are looking for something like this
{
"p": 1,
"s": [
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 3
},
{
"a": 3,
"b": 4
}
]
}
For this code will be like as below
JSONArray jArray = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject job= new JSONObject();
job.put("a",objectList.get(i).getA());
job.put("b",objectList.get(i).getB());
jArray .put(job);
}
try {
jOuter.put("s", jArray );
} catch (JSONException e) {
e.printStackTrace();
}
Please check following code: This will make the proper formatting:
JSONObject jo = new JSONObject();
try {
jo.put("p", "1");
JSONArray jarr = new JSONArray();
for (MyObject listItem : objectList) {
JSONObject inner = new JSONObject();
inner.put("a", listItem.getA());
inner.put("b", listItem.getB());
jarr.put(inner);
}
jo.put("s", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return output like:
{
"p":1,
"s":[{"a":1,"b":2},{"a":2,"b":3},{"a":3,"b":4}]
}
This makes a proper json, which I think you need! Do let me know, if I am wrong somewhere.

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

Android convert JSONArray to String Array

I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
if (jsonStr != null) {
try {
foodsFilter = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foodsFilter.length(); i++) {
JSONObject c = foodsFilter.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String filter_type = c.getString(TAG_FILTER_TYPE);
//String item_list = c.getString(TAG_ITEM_LIST);
JSONArray itemList = new JSONArray(c.getString("item_list"));
String item_list = itemList.toString();
// tmp hashmap for single contact
HashMap<String, String> filter = new HashMap<String, String>();
// adding each child node to HashMap key => value
filter.put(TAG_CATEGORY_NAME, category_name);
filter.put(TAG_FILTER_TYPE, filter_type);
filter.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodsFilterList.add(filter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]
I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}
So I can send it into another activity use Intent and show it in ListView
What you have
String item_list = itemList.toString();
You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}
Now you can add the strings to a list/array and then do what is required.
Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}

How to convert string json to JSONArray?

How can I convert this string into JSONArray ?
{"result":{"passion":[{"id":2,"description":"Sushi"},{"id":3,"description":"Dinner"},{"id":4,"description":"Sex"},{"id":5,"description":"Boobies"},{"id":6,"description":"Sleep"},{"id":7,"description":"Cars"},{"id":8,"description":"Travel"},{"id":9,"description":"Soccer"},{"id":10,"description":"Silice"}]}}
I'm trying to do:
JSONArray jsonArray = jsonObject.getJSONArray("passion");
But I am getting an exception:
org.json.JSONException: No value for passion
is seems like you are not getting result object
JSONArray jsonArray = jsonObject. getJSONObject("result").getJSONArray("passion");
may be this is what you need dear
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Use this code
JSONObject jsonObject = new JSONObject(json);
JSONObject resultValues = jsonObject.getJSONObject("result");
JSONArray passionArray = resultValues.getJSONArray("passion")

Categories