I am sending API call to a service that return a json array like this :
[Object, Object ....]
via my java http request. the resulat are stored in a string:
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
I need to find a way to split this string to by json objects so each new string will contain only one object.
Thanks.
Instead of using the split function, you can convert your String to a JSONArray and then iterate throw the array
JSONArray jsonArray = new JSONArray(response.toString());
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String jsonObjectAsString = jsonObject.toString();
}
Related
This has probably been asked before, but I do not know the terminology for my question, therefore do not know what to look up.
I am using GSON and Java trying to get information from a parsed JSONElement.
Java code:
JsonParser parser = new JsonParser();
String url = "https://chapel-logs.herokuapp.com/attendance";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
JsonElement element = parser.parse(response.toString());
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
System.out.println(albums.get("students")); //prints out data in students
System.out.println(albums.get("students.LastChapelAttended")); //error
}
My JSON :
{"students":[{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":6,"Hour":15,"Min":14,"Sec":28},"StudNum":"F02660934","Attendance":17},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":5,"Hour":19,"Min":49,"Sec":11},"StudNum":"002660934","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":4,"Hour":20,"Min":35,"Sec":57},"StudNum":"002643472","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":7,"Hour":5,"Min":34,"Sec":54},"StudNum":"002664906","Attendance":1}]}
The data I am trying to get is: LastChapelAttended, however LastChapelAttended is within students. In JavaScript the equivalent to what I am trying would be students.LastChapelAttended if that helps.
Thanks in advance!
JsonObject jObj=(JsonObject)albums.get("students").getAsJsonArray().get(0);
System.out.println(jObj.get("LastChapelAttended"));
Get it as a JsonArray and then loop through the array to get LastChapelAttended.
First, students is not an object but an array. Thus students.LastChapelAttended should not work in any language. If you want to retrieve LastChapelAttended of the first student in the array students[0].LastChapelAttended should work.
I am not familiar with gson, but I think what you want to do is something like this:
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
JsonArray students = albums.getAsJsonArray("students");
for (JsonElement student : students) {
System.out.println(albums.getAsJsonObject().get("LastChapelAttended"));
}
}
You can check this out for help Difference between JSONObject and JSONArray
Students is a JsonArray
LastChapelAttended is a JSONObject you can get it by calling
json = (json data)
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray studentsArray = rootObj.getAsJsonArray("students");
for (JsonElement stu : studentsArray) {
JsonObject student = stu.getAsJsonObject();
JsonObject LastChapelAttended = student.getAsJsonObject("LastChapelAttended");
}
Just iterate over the student array
albums.getAsJsonArray("students")
.forEach(student -> System.out.println(student.getAsJsonObject()
.get("LastChapelAttended")));
I am currently developing an app and need to parse JSON objects from inside an unnamed array.
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt.
The code that I used for the one above is
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String asd = buffer.toString();
JSONObject parentObject = new JSONObject(asd);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject fObject = parentArray.getJSONObject(0);
String movie = fObject.getString("movie");
int year = fObject.getInt("year");
return movie + year;
The code includes "movies" which is the array name .
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all?
Your countries list is simply an array. Doesn't need a name.
Simply replace
JSONObject parentObject = new JSONObject(asd);
with
JSONArray parentObject = new JSONArray(asd);
See this post for how to iterate over that array to parse the remainder of the objects.
How to parse JSON in Android
Starting something like
for (int i=0; i < parentObject.length(); i++) {
Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself.
My request body contains JSON. i have to read that JSON save it as JSON object. And i don't have any pojo class representing the data in json. i tried this , and this and i am using com.ibm.json.java.JSONObject.i have tried this ,
BufferedReader ne = req.getReader();
StringBuffer jb = new StringBuffer();
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", jb.toString());
above implementation is dumb because i am converting request header to string and adding it to jsonobject.
I think you should use public static JSONObject parse( java.lang.String str) in class JSONObject .Also there is no need to convert Reader to String as there are overloaded methods in JSONObject which take Inputstream and Reader eg public static JSONObject parse( java.io.Reader reader)
I have string in JSON format. For example:
{
"blockedStatus":true,
"cars":[
"RAW:123",
"TVU:123"
],
"phones":[
"370665566",
"3706324231"
]
}
This is output from server. I need to get seperate values but I don't know how to do it.
Tried this:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
Log.e("IO-OUTPUT", builder.toString()); //prints json output
Log.e("finalResult (1)", finalResult.getString(1));
But I get ant exception:
W/System.err(31249): org.json.JSONException: Value {"blockedStatus":true,"cars":["RAW"],"phones":["65431"]} of type org.json.JSONObject cannot be converted to JSONArray
Is there another way to get values? Because calculating symbols and getting values from it will be too hard
change
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
to
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray carsResult = jsonObject.getJSONArray("cars");
JSONArray phoneResult = jsonObject.getJSONArray("phones");
your string rapresent a JSONObject which contains two JSONArray's, cars and phones, and a pair key/value blockedStatus .
Also, if you read the logcat, it says:
type org.json.JSONObject cannot be converted to JSONArray
You can not convert a JSONObject to a JSONArray, which means the you have a JSONObject
Try this
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
responseString = response.toString();
responseString = intputStreamToStringConvertor(ips);
JSONObject object = new JSONObject(responseString);
Boolean status = object.getBoolean("blockedStatus");
JsonArray cars = object.getJSONArray("cars");
JsonArray phones = object.getJSONArray("phones");
I need my app to send an ArrayList<String[]> to php, I have this to call the service:
ArrayList<String[]> Items = new ArrayList<String[]>();
(...)
JSONObject JSONSend= new JSONObject();
JSONSend.put("Items", Items );
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(SERVICE);
post.setHeader("json", JSONSend.toString());
StringEntity se = new StringEntity(JSONSend.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
and on the PHP service:
$data = file_get_contents('php://input');
$json = json_decode($data);
$Items = $json->{'Items'};
error_log($Items);
and the php is returning this:
[[Ljava.lang.String;#413e2fd0, [Ljava.lang.String;#413a2940, [Ljava.lang.String;#4139df18, [Ljava.lang.String;#4141b5b0, [Ljava.lang.String;#413931c8, [Ljava.lang.String;#41348b40, [Ljava.lang.String;#41393928]
The type of the $ServMade is string, so how can I take care of the data as an array on php? Am I missing something?
Try the following when generating json string in android:
JSONObject JSONSend= new JSONObject();
JSONArray ja = null;
JSONArray tmp = new JSONArray();
for(String s[] : Items){
ja = new JSONArray();
for(int i = 0; i<s.length; i++)
ja.put(s[i]);
tmp.put(ja);
}
JSONSend.put("Items", tmp);
The problem here is that You call .toString() (within Java) on an array of strings (String[]) that while NOT overrided returns exactly what You get in the JSON: [Ljava.lang.String;#413e2fd0].
Don't know exactly the JSONObject but I guess You should transform the ArrayList<String[]> (so the array of arrays of strings) to something different for JSONObject to handle it correctly.
Also, in PHP, You do not have to call $Items = $json->{'Items'}; - it is okay to call $Items = $json->Items;.