Use values (integers) returned in JSONArray - java

Im having issues with being able to get the indivisual responses from this JSON Array. Im trying to write some code that will allow me to use the vaules indivisually, as well as how to combine them if i needed too. These responses are always integers.
Java
JSONObject jsonObj = new JSONObject(jsonStr);
data_array = jsonObj.getJSONArray("data");
for (int i = 0; i < data_array.length(); i++) {
JSONObject prod = data_array.getJSONObject(i);
Log.d("Logging Response", prod);
}
Json
[5652,8388,8388,7537,8843,2039,8235,0,12220]
I'd like to figure out how i can add them together and return the calculated result, as well as how to use them individually. such as (prod + prod + prod) etc...

JSONArray data = jsonObj.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
Integer prod = (Integer) data.get(i);
System.out.println("Prod " + prod);
// loop and add it to array or arraylist
}

You have the jsonarray as the response
ArrayList<Integer> jsonvalue=new ArrayList<Integer>();
for (int i = 0; i < data_array.length(); i++) {
int i= data_array.getInt(i);
jsonValue.add(i)
}

To put that json array data in to a new json object, try this:
JSONObject jsonObj = new JSONObject(jsonStr);
data_array = jsonObj.getJSONArray("data");
JSONObject prod;
for (int i = 0; i < data_array.length(); i++) {
prod.put(i,data_array.getJSONObject(i));
Log.d("Logging Response", prod);
}

JSONArray jsonObj = new JSONArray(jsonStr);
for (int i = 0; i < jsonObj.length(); i++) {
System.out.println(jsonObj.getString(i));
}

Related

Get a Value from a JsonArray and store it in array

I am trying to extract "score from the following set of ArrayofJson
I just want, score 1,2,1,3 store in an array. like int sample[] = {1,1,1,1,1,1,1,1,1};
how can we do it?
import org.json.JSONArray;
import org.json.JSONObject;
public static void main(String args[]) {
JSONArray jsonArray = new JSONArray(
"[{\"Qnum\":1124,\"Response\":\"London\\n\",\"SelectedResponse\":\"1\",\"Score\":1.0},{\"Qnum\":1125,\"Response\":\"Sydney\\n\",\"SelectedResponse\":\"2\",\"Score\":2.0},{\"Qnum\":1126,\"Response\":\"Paris\\n\",\"SelectedResponse\":\"1\",\"Score\":1.0},{\"Qnum\":1183,\"Response\":\"NewYork\\n\",\"SelectedResponse\":\"3\",\"Score\":3.0}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
Iterator<String> keys = json.keys();
System.out.println(json.getDouble("Score"));
}
JSON Array looks like this [1,2,3,4], not {1,2,3,4}
This can help you.
// If You Wanted to have JSONArray
List<Double> scores = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scores.add(score);
}
JSONArray array = new JSONArray(scores);
System.out.println(array);
// If You Wanted to have Java Array of double
double []scoresDouble = new double[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scoresDouble[i] = score;
}
System.out.println(Arrays.toString(scoresDouble));
// If You Wanted to have Java Array of int (as mentioned on the questing)
int []scoresInt = new int[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scoresInt[i] = (int) score;
}
System.out.println(Arrays.toString(scoresInt));

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

StringIndexOutOfBoundsException with ArrayList

i am trying to make an app that requires to loop through an array of JSON objects. For this i first create an ArrayList and then convert it to an Array and loop through it, however i get the following error:
Day::drawEvents |
StringIndexOutOfBoundsException: length = 16;
regionStart = -2;
regionLength = 1
The error doesn't even show up on the logcat as an error it only displays as popup message on the device.
The code that i suspect causes the error:
List<JSONObject> appointments = new ArrayList<JSONObject>();
JSONObject jsonObject = new JSONObject(jsonAppointments);
JSONObject jsonResponse = jsonObject.getJSONObject("response");
JSONArray jsonData = jsonResponse.getJSONArray("data");
for (int i = 0; i < jsonData.length(); i++) {
appointments.add(jsonData.getJSONObject(i));
}
List<JSONObject> appointments = new ArrayList<JSONObject>();
...adding items to the ArrayList...
JSONObject[] appointmentsArray = new JSONObject[appointments.size()];
appointments.toArray(appointmentsArray);
int len = appointments.size();
for (int i = 0; i < len; i++) {
start = appointmentsArray[i].getInt("start") * 1000L;
...processing the array content...
}

JSON to Hold Course, Student, and Assignment Data

I am trying to use JSON to contain data related to a class/course. The idea is that there are 40 classes/courses and that each class/course contains 50 students, and each student has 100 assignments. Below is what I've figured out so far. How can I modify it to hold all the gradebook data, as listed above?
public void x(){
JSONObject courseJSONObject = new JSONObject();
JSONArray courseJSONArray = new JSONArray();
JSONObject studentJSONObject = new JSONObject();
JSONArray studentJSONArray = new JSONArray();
JSONObject assignmentJSONObject = new JSONObject();
JSONArray assignmentJSONArray = new JSONArray();
for(int i = 0; i < 40; i++){
courseJSONObject.put("course name", course.getName());
courseJSONObject.put("course teacher", course.getTeacher());
courseJSONArray.put(courseJSONObject);
courseJSONObject = new JSONObject();
for(int j = 0; j < 50; j++){
studentJSONObject.put("student name", course.student.getName());
studentJSONObject.put("student id", course.student.getid());
studentJSONObject.put("student final grade",
course.student.getfinalgrade());
studentJSONArray.put(studentJSONObject);
studentJSONObject = new JSONObject();
for(int k = 0; k < 100; k++){
assignmentJSONObject.put("assignment name", getAssignmentName());
assignmentJSONObject.put("category", getAssignmentCategory());
assignmentJSONObject.put("date", getAssignmentDate());
assignmentJSONObject.put("grade",
course.student.getAssignmentGrade());
assignmentJSONArray.put(assignmentJSONArray);
assignmentJSONObject = new JSONObject();
}
}
}
JSONArray courses = new JSONArray();
for(int c = 0; i < 40; c++) {
JSONObject course = new JSONObject();
// Add course details
JSONArray students = new JSONArray();
for(int s = 0; s < 50; s++) {
JSONObject student = new JSONObject();
// Add Student details
JSONArray assignments = new JSONArray();
for(int a = 0; a < 100; a++) {
JSONObject assignment = new JSONObject();
// Add assignment details
assignments.put( assignment );
}
student.put( "assignments", assignments );
students.put( student )
}
course.put( "students", students );
courses.put( course );
}

How to parse JSON Array of String in android

this is the response from the server
{"route":[1,2,3,4,5,6]}
This is my code:
try{
String d = json.getString("route");
}
}catch(JSONException je){
}
and im getting NullPointerException.
please help me.
This is my Server Response, Now Give me the solution
Link -> http://ajax.tpksym.cloudbees.net/route/route14
It should be like:
JSONObject jsonResult = new JSONObject("{\"route\":[1,2,3,4,5,6]}");
JSONArray array = jsonResult.getJSONArray("route");
for (int i = 0; i < array.length(); i++) {
int data = array.getInt(i);
}
....
try {
String jsonString = "{\"route\":[1,2,3,4,5,6]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("route");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getInt(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi as yours json is as follows
{
"route": [
1,
2,
3,
4,
5,
6
]
}
so do as follows
String jsondata = "{\"route\":[1,2,3,4,5,6]}";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Integer data = jarray.getInt(i);
System.out.println("data=="+data);
}
as you gave the link http://ajax.tpksym.cloudbees.net/route/route14
and data seems there coming as in double i.e. 13.56 etc
so use as follows
String jsondata = "JSON DATA FROM SERVER";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Double data = jarray.getDouble(i);
}

Categories