Writing into JSONArray - java

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

Related

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

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

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

How do I parse this JSON in Java?

I'm a bit new to this and it's doing my head in! I keep getting this error:
Error parsing data org.json.JSONException: No value for tname
This is the json:
[{"tname":"2"},{"kword":"||ice+skating+rink"}]
And here is my java code:
String result = response.toString();
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", ", type: " + json_data.getString("tname")+
", keyword: " + json_data.getString("kword"));
type += json_data.getString("tname");
keyword += json_data.getString("kword");
}
Any help greatly appreciated.
Your second object doesn't have tname. you should check and see if the object has a property before accessing it
if(json_data.has("tname"))
type += json_data.getString("tname");
if(json_data.has("kword"))
keyword += json_data.getString("kword");

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