single array json parser in java - 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);
}

Related

want to store multiple JSON objects to jsonArray and get the result as a single string

Here is my code for storing multiple JSON objects into an array and then I want to convert the array into a single string.
String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");
JSONArray array = new JSONArray();
for(int i= 0; i<= array.length(); i++) {
array.put(json);
message = array.toJSONString();
}
I want to get the output as a string and store it in a message variable.
String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");
JSONArray array = new JSONArray();
//for(int i= 0; i<= array.length(); i++) {
// array.put(json);
// message = array.toJSONString();
//}
array.put(json); //There is a JSON,just put it into the array
message = array.toJSONString();
I was replacing "name" every time I was calling json.put()
String message =null;
JSONObject json = new JSONObject();
json.put("name","Atal");
json.put("class", "10");
json.put("Roll","1035");
JSONArray array = new JSONArray();
array.put(json);
message = array.toJSONString();

Java - retrieving JSON object values

i have a JSON object which looks something like this:
cb = {"content":[{"name":"abc"}{"name":"bcd"}{"name":"xyz"}...]}
and i have imported the JSON library as:
import org.json.JSONObject;
Now i want to use a for loop to retrieve the values of name in each of the sub objects...
for(int x = 10; x < numberOfSubElemtnts; x = x+1) {
//print out the name values
}
Output should be:
abc
bcd
xyz
How should I evaluate the length of the array and print out the name values?
You can iterate the array like this:
String content = "{\"content\":[{\"name\":\"abc\"},{\"name\":\"bcd\"},{\"name\":\"xyz\"}]}";
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("content");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("name"));
}
JSONParser parser = new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
for(int i=0;i<array.length();i++{
System.out.println(array.get(i).getString("name");
}
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
Also with this example youll have to change the format of your string to fit the one I have in mine

How to access key:values in JSON using Java with no array names

Lets say I have a JSON array like this
[{"a":"1", "b":"2"}, {"c":"3", "d":"4"}]
I'm trying to get it in Java like this
JSONArray array = new JSONArray(responseBody); //resposeBody is the JSON array
for (int i = 0; i < array.length(); i++) {
String arr = array.get(i).toString(); //Trying to get each array like this
JSONArray json = new JSONArray(arr);
}
At the line of JSONArray json = new JSONArray(arr);I get the error
A JSONArray text must start with '['
How do I access the values?
EDIT: I mean how do I get each array and their values
Your JSONArray is an array of JSONObjects.
You can try
JSONArray array = new JSONArray(responseBody);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
}
Now you can further parse the individual JSONObjects.
Just do :
JSONObject myJsonObject = new JSONObject(jsonString);
In array:
JSONObject myjObject = myJsonArray.getJSONObject(i);

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

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