How to convert string json to JSONArray? - java

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")

Related

Parse json in Java android studio

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

single array json parser in java

I have a json string which i need to parse using java. Format is -
input = {"data":{"value":[654,123]},"address":null,"code":null}
From this i need only "value":[654,123]
I tried but this -
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(input);
JSONArray jsonarr_1 = (JSONArray) jobj.get("value");
System.out.println(jsonarr_1);
for(int i=0;i<jsonarr_1.size();i++)
{
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONArray jsonarr_2 = (JSONArray) jsonobj_1.get("value");
System.out.println("values under value array");
System.out.println(jsonarr_2);
}
}
is first level of json array and giving nullpointerexception
You first need to get data Json object and then read the value array from that.
You can see working code below:
String input = "{\"data\":{\"value\":[654,123]},\"address\":null,\"code\":null}";
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject) parse.parse(input);
JSONObject dataObj = (JSONObject) jobj.get("data");
JSONArray jsonarr_1 = (JSONArray) dataObj.get("value");
System.out.println(jsonarr_1);
for (int i = 0; i < jsonarr_1.size(); i++) {
System.out.println("values under value array");
long value = (long) jsonarr_1.get(i);
System.out.println(value);
}

Value Next of type java.lang.String cannot be converted to JSONArray

I'm trying to save json_data from server to sqlite, but i'm getting the error
Value Next of type java.lang.String cannot be converted to JSONArray
Here is my json : My Json
And here is my java code :
String json_data = stringBuilder.toString().trim();
JSONObject object = new JSONObject(json_data);
JSONObject object1 = new JSONObject("Next");
JSONArray Jarray = object1.getJSONArray("Days");
for (int i = 0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = Jarray.getJSONObject(i);
dbHelper.putStationsInformation((Jasonobject),sqLiteDatabase);
}
dbHelper.close();
I know this code looks weird but please help me do this.
You need to fetch Next jsonobject instead of creating it here with a single String like
new JSONObject("Next"); , so fetch it from response object like
JSONObject object1 = object.getJSONObject("Next");
"Value Next of type java.lang.String cannot be converted to
JSONArray".
Rectify getJSONObject section.
Dont
JSONObject object1 = new JSONObject("Next");
Do
JSONObject obj = new JSONObject(json_data );
JSONObject _jsonOBJ = obj.getJSONObject("Next");
JSONArray Jarray = _jsonOBJ .getJSONArray("Days");
for (int i = 0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = Jarray.getJSONObject(i);
dbHelper.putStationsInformation((Jasonobject),sqLiteDatabase);
}
JSONObject result_obj= new JSONObject(result.toString());
JSONObject result_array= result_obj.getJSONObject("Next");
JSONArray array_values = result_array.getJSONArray("Days");
for (int i = 0; i < Jarray.length(); i++)
{
JSONObject plan = Jarray.getJSONObject(i);
plan.getString("Day");
for(int j=0;j<plan.lenght();j++){
}
}
You need to Parse the "Next" object from the json provided. You have created a new JSONObject that was the mistake.
try {
String json_data = stringBuilder.toString().trim();
JSONObject object = new JSONObject(json_data);
JSONObject object1 =object.getJSONObject("Next");
JSONArray Jarray = object1.getJSONArray("Days");
for (int i = 0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = Jarray.getJSONObject(i);
dbHelper.putStationsInformation((Jasonobject),sqLiteDatabase);
dbHelper.close();
}
} catch (JSONException e) {
e.printStackTrace();
}
Happy coding!!
You have created a new JSONObject("Next")which means you are converting a string "Next" into a JSONObject.
Rectify to this:
String json_data = stringBuilder.toString().trim();
JSONObject object = new JSONObject(json_data);
JSONObject object1 = object.getJSONObject("Next");

iterate through JSONArray in java

I have a JSONArray :
public JSNArray getItems() {
JSONArray listjson = new JSONArray();
JSONObject fnl_json = new JSONObject();
//adding few items to fnl_json
listjson.add(fnl_json);
return fnal_json;
}
I am calling getItems function, how can I iterate through fnl_json from the called function?
To iterate a JSONArray you can do:
JSONObject jsonObject = new JSONObject("jsonString");
JSONArray jsonArray = jsonObject.getJSONArray("arrayName");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i); // you will get the json object
//do the stuff
}

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

Categories