Parsing JSON Array within JSON Object - java

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

Related

How to Get String From Parse JSON without String Id in Android Studio

How do I get a string from Parse JSON with data like below?
My Data JSON :
[
[
"John Gorman",
"3344764667200003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Andy William",
"3403032311690003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Thomas Endry",
"3408932311690078",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Robet Calm",
"3403077711690890",
"Student",
"2018-08-09 08:21:30.807"
]
]
I use the code below, then to get the string what I have to do, I really don't understand, if there is help, I really need to thank you.
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("What should I write here");
System.out.println(c.getString(""));
}
I want to get the string from Parse JSON that I have
How do I get a string for listview, for example:
John Gorman
3344764667200003
Student
Andy William
3403032311690003
Student
Thomas Endry
3408932311690078
Student
Robet Calm
3403077711690890
Student
A couple of things are wrong with the posted code. See my comments inline:
JSONObject object = new JSONObject(result);
^^^^^^^^^^^^^^^^^^^^^^
the content of result is not an object, but an array!
JSONArray jsonArray = object.getJSONArray("");
^^
a proper JSON document had better not have empty keys!
//JSONArray jsonArray = new JSONArray(result);
^^^^^^^^^^^^^^^^^^^^^
this was actually going in the right direction!
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
^^^^^^^^^^^^^^^^^^^^^^^^^^
the i-th element of the array is not an object, but an array!
Fixing the issues above:
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray subArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subArray.length(); j++) {
System.out.println(subArray.getString(j));
}
System.out.println();
}
You are receiving a JSONArray not object so use the below code.
for(int i=0;i<jsonarray.length();i++){
JSONArray array=jsonarray.getJSONArray(i);
for(int j=0;j<array.length();j++){
Log.d(TAG,array.getString(j));
}
}
You can do something like this:
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(0);
String id = c.getString(1);
String student = c.getString(2);
// and so on ... This index refers to the index number on the string inside json object
System.out.println(name);
}
Hope this answers your query.
Following method will construct a list of string from the given Json. You can pass that list in the adapter of the list view.
public List<String> getList (String result) throws JSONException {
List<String> list = new LinkedList<>();
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray arr = jsonArray.getJSONArray(i);
StringBuilder sb = new StringBuilder();
for(int j=0;j<arr.length(); j++) {
sb.append(arr.getString(j));
if(j<arr.length()-1) sb.append("\n");
}
list.add(sb.toString());
}
return list;
}

retrieving the value in a json array encounters errors

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++;
}

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

Android - Parse PHP json_encode to Java

String json_string_from_server = "{\"test1\":\"test1_value\",\"test2\":\"test2_value\"}";
how to loop the JSON and print all the keys and values.
You can simply parse the Json string as below -
String json_string_from_server = "{\"test1\":\"test1_value\",\"test2\":\"test2_value\"}";
JSONObject jObj = new JSONObject(json_string_from_server);
String val_Test1 = jObj.getString("test1");
String val_Test2 = jObj.getString("test2");
case 2:
String json_string_from_server = "{
"result" : [
{\"test1\":\"test1_values_baru\", \"test2\":\"test2_values\"},
{\"test1\":\"test‌​1_values\", \"test2\":\"test2_values\"}
]
}";
JSONObject jObj = new JSONObject(json_string_from_server);
JSONArray jResultArray = jObj.getJSONArray("result");
for(int i=0; i<jResultArray.length(); i++){
JSONObject jResultObj = jResultArray.getJSONObject(i);
String val_Test1 = jResultObj.getString("test1");
String val_Test2 = jResultObj.getString("test2");
}
Suppose jsonString is a variable in which you get all your json from php. You will need to iterate the array as follows:
JSONArray arr = new JSONArray(JsonString);
for(int i=0; i<= arr.length(); i++)
{
JSONObject obj = arr.get(i);
obj.getString('test1'); // these are your strings
obj.getString('test2');
}
String json_string="[{\"test1\":\"test1_values_baru\",\"test2\":\"test2_values\"},{\"test1\":\"test‌​1_values\",\"test2\":\"test2_values\"}]";
JSONArray jResultArray = new JSONArray(json_string);
for(int i=0; i<jResultArray.length(); i++){
JSONObject jResultObj = jResultArray.getJSONObject(i);
String val_Test1 = jResultObj.getString("test1");
String val_Test2 = jResultObj.getString("test2");
}

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