retrieving the value in a json array encounters errors - java

Output of String return: [{"type":1, "txt":"ERROR"}]. I'm trying to get the content of txt key which is ERROR. And that
by transforming string return into an array. However I'm getting some errors commented next to each line on the follow code.
Any insight? I tried everything to retrieve the value of txt.
Vector<ClsReturn> ret = null;
ret = ds.id(collection, "fs",in_uri );
String return = JSONArray.toJSONString(ret);
JSONObject myJsonObject = new JSONObject(ret);
JSONArray array = new JSONArray(return); //The constructor JSONArray(String) is undefined
for(int i=0; i<array.length(); i++){ //The method length() is undefined for the type JSONArray
JSONObject jsonObj = array.getJSONObject(i); //The method getJSONObject(int) is undefined for the type JSONArray
System.out.println(jsonObj.getString("txt"));
}

Try this
String retur = JSONArray.toJSONString(ret);
JSONObject myJsonObject = new JSONObject();
JSONArray array = new JSONArray(retur);
int i = 0;
while(i < array .length()){
myJsonObject = array .getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}

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

Parsing JSON Array within JSON Object

I have some JSON with the following structure:
{"source":[
{"name":"john","age":20},
{"name":"michael","age":25},
{"name":"sara", "age":23}
]
}
I have named this JSON string as mainJSON. I'm trying to access the elements "name" and "age" with the following Java code:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
for (int i = 0; i < jsonMainArr.length(); i++) { // **line 2**
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
int age = childJSONObject.getInt("age");
}
I'm being shown the following exception for line number 2:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
Please guide me as to where I'm making the mistake and how to rectify this.
mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.
The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)
Try this:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
String jsonText = readAll(inputofyourjsonstream);
JSONObject json = new JSONObject(jsonText);
JSONArray arr = json.getJSONArray("sources");
Your arr would looks like: [
{
"id":1001,
"name":"jhon"
},
{
"id":1002,
"name":"jhon"
}
]
You can use:
arr.getJSONObject(index)
to get the objects inside of the array.
This could be an answer to your question:
JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
String name = msg1.getString("name");
int age = msg1.getInt("age");
}

Categories