How to send an JSON array to another method - java

I am fetching an JSON response from an API.
I should return those JSON response to another method with selected fields
Here I am fetching all the JSON response and putting it to an JSONArray which I should return to another method.
How to fetch both String and Long returning fields and put it into an JSON array and return it to another method
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("/2.0/clusters/list");
request.addHeader("Authorization", "bearerToken");
request.addHeader("cache-control", "no-cache");
HttpResponse response = client.execute(request);
System.out.println("Response Code:" +
response.getStatusLine().getStatusCode());
String json = EntityUtils.toString(response.getEntity());
System.out.println("Gather Details\n");
JSONObject cluster = new JSONObject(json);
JSONArray clusterJsonArray = cluster.getJSONArray("clusters");
for (int i = 0; i < clusterJsonArray.length(); i++) {
JSONObject iteratingObj = array.getJSONObject(i);
String id = iteratingObj.get("id").toString();
String time = iteratingObj.get("time").toString();
System.out.println("Id:" + id + "time:" + time + "\n");
List<String> strList = new ArrayList<>();
for (int p = 0; p < clusterJsonArray.length(); p++) {
strList.add(clusterJsonArray.getJSONObject(p).getString("id"));
strList.add(clusterJsonArray.getJSONObject(p).getString("time"));
}
System.out.println("Arr:" + strList);
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("Failed HTTPresponse" + response.getStatusLine().getStatusCode() + "" + json);
}
}
Help me out to send the response with selected fields to other method in which that JSONarray should take both String and Long values and store it in one varible of JSONArray.
Here is the incoming JSON:
"clusters": [
{ "id": "0411-0089ki", "driver": { }, "start_timestamp": 1568952332573, },
Here JSONObject["time"] not a string is the error i am facing when i am putting it to JSONArray

The intention of the above code you mentioned is not clear. But,
Here JSONObject["time"] not a string is the error i am facing when i
am putting it to JSONArray
You can use:
long time = iteratingObj.getLong("start_timestamp");
But you do not use the local variables of id and time in anywhere.
I think the logic is incorrect in the code that you put in the question. Please double check the logic for these 2 loops.
for (int i = 0; i < clusterJsonArray.length(); i++) {
for (int p = 0; p < clusterJsonArray.length(); p++) {

Related

Writing into JSONArray

I'm reading JSON file, taking out the values and doing some changes.
Basically I added some values to array. After that I want to write it back on a file. When I write JSONArray back to file is written as string and not JSONArray object. How can I write it well?
In the following code I'm writing into JSON file:
JSONArray rooms = (JSONArray) jsonObject.get("rooms");
for (int i = 0; i < rooms.size(); i++) {
JSONObject room = (JSONObject) rooms.get(i);
String roomName = (String) room.get("roomName");
System.out.println("RoomName: " + roomName + " Size: " + "O: " + oldRoomListSize.get(roomName) + " N: " + roomList.get(roomName).getRoomBook().size());
if(oldRoomListSize.get(roomName) < roomList.get(roomName).getRoomBook().size()) {
int n = roomList.get(roomName).getRoomBook().size() - oldRoomListSize.get(roomName);
for (int j = n; j > 0; j--) {
int lenght = roomList.get(roomName).getRoomBook().size();
JSONArray schedule = (JSONArray) room.get("schedule");
Reservation r = roomList.get(roomName).getRoomBook().get(lenght-j);
schedule.add(r);
}
}
}
fileWriter.write(jsonObject.toJSONString());
fileWriter.close();
As you can see, is being written as string and it bring me problems when I want to read it back.
"schedule":["{Day: 1 - Start Time: 10}"]
File Reader:
JSONArray schedule = (JSONArray) room.get("schedule");
for (int j = 0; j < schedule.size(); j++) {
JSONObject s = (JSONObject) schedule.get(j);
String day = (String) s.get("day");
String startTime = (String) s.get("startTime");
lRoom.setRoomBook(Integer.parseInt(day), Integer.parseInt(startTime));
}
Error: java.lang.ClassCastException: java.lang.String cannot be cast
to org.json.simple.JSONObject
Error occurs, after enter new value to array (Introduced day and start time). It's writen as string, and when i try to read it again, give me a error saying i cant parse it since there's a string on array.
Input file:
{
"rooms":[
{"maxOccupants":"10",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"20","day":"20"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"1",
"floor":"2",
"roomName":"room1"},
{"maxOccupants":"4",
"schedule":[{"startTime":"10","day":"1"},{"startTime":"11","day":"122017"},{"startTime":"11","day":"15"}],
"tv":"false",
"mobilePhone":"false",
"projector":"false",
"buildID":"1",
"floor":"2",
"roomName":"room2"},
{"maxOccupants":"5",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"2",
"floor":"3",
"roomName":"room3"}
]
}
Problem solved! I was not creating a JSONObject, so I was introducing a directly object to JSON Array and it forced conversation to String.
Here is the resolution of the problem:
JSONObject jsonObj = new JSONObject();
String startTime = String.valueOf(r.getStartTime());
String day = String.valueOf(r.getDay());
jsonObj.put("startTime", startTime);
jsonObj.put("day", day);
schedule.add(jsonObj);

Parse multiple of the same key JSON simple java

I'm not an expert at JSON so I'm not sure if I'm missing something obviously. But, what I'm trying to do is to parse this:
[{"name":"Djinnibone"},{"name":"Djinnibutt","changedToAt":1413217187000},{"name":"Djinnibone","changedToAt":1413217202000},{"name":"TEsty123","changedToAt":1423048173000},{"name":"Djinnibone","changedToAt":1423048202000}]
I don't want to get Djinnibone only the rest of the names following it. What I've managed to create is this. It give the right number of names. but they are all null. In this case null,null,null,null .
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject();
for(int index = 1; index < response.size(); index++) {
jsonObject.get(response.get(index));
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}
Thanks for any help!
You're almost there, you're getting each JSONObject from the array but you're not using it correctly. You simply need to change your code like this in order to extract each object and use it directly, no need for an intermediate JSONObject creation:
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for(int index = 1; index < response.size(); index++) {
JSONObject jsonObject = response.get(index);
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}

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 issue with json

I'm trying to parse the json data that I get back from lastfm.
The method I'm interested in is album.search
The documentation requires there to be a search term for the album name, and an api key, which I've done here:
String api_key = "x";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search" +
"&album="
+ query
+ "&apikey="
+ api_key
+ "&format=json";
Then my issue was trying to iterate through the json data so I can get to the value that I wanted, in my case, name, so I made an array to loop through the json file.
boolean error = false;
HttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
HttpResponse data = httpclient.execute(new HttpGet(url));
HttpEntity entity = data.getEntity();
String result = EntityUtils.toString(entity, "UTF8");
for ( int i = 0; i < results.length(); i++) {
JSONObject row = new JSONObject(result);
albummatches = row.getString("albummatches");
album = row.getString("album");
name = row.getString("name");
results.getJSONObject(i).get("album");
I have this method which returns results.
public JSONArray getResults() {
return results;
}
Now in my other class, I'm trying to attach the name of the album to my adapter list view through this method.
public void ServiceComplete(AbstractService service) {
if (!service.hasError()) {
AlbumSearchService albumService = (AlbumSearchService)service;
String[] result = new String[albumService.getResults().length()];
for (int i = 0; i < albumService.getResults().length(); i++) {
try{
result[i] = albumService.getResults().getJSONObject(i).getString("name");
} catch (JSONException ex) {
result[i] = "Error";
}
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.album_list_cell, R.id.text, result));
}
But unfortunately, when I try to run the app, and search for an album, it just stays stuck on 'searching...', and doesn't display any results in my list view.
I don't know where I'm going wrong :( Help someone!

Get JSON String in java with org.json

[{"post":{"titel":"Glee","interpret":"Bran Van 3000","jahr":"1997","id":"5"}},{"post":{"titel":"Goodbye Country (Hello Nightclub)","interpret":"Groove Armada","jahr":"2001","id":"4"}},{"post":{"titel":"Beauty","interpret":"Ryuichi Sakamoto","jahr":"1990","id":"1"}}]
The above string is what i have in json and now what i want to do is to just get the values of "post" and "titel" as in the above string what i am having 3 values of post which makes sense to me. But, now what i want is to print all the 3 values of post and each value in the post string.
JSONArray jsonArray = new JSONArray(jsonString);
columns = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
columns[i]=jsonObject.getString("post");
}
above code returns me 3 values of post. WHat i can do if i want to print values of post and the each value of column in post?
I would do something like this (I don't use the columns array just to print, and this code is not tested):
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject postObj = jsonObject.getJSONObject("post");
for (String i : postObj.keys()) {
System.out.println("Key: " + i + "; Value: " + postObj.getString(i));
}
}
That is, process each element of the Object returned by the "post" object of each array element.

Categories