Parse multiple of the same key JSON simple java - 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;
}

Related

I am not able to get the data from a Json array

Error message: com.example.myjson W/System.err: org.json.JSONException: Value
of type org.json.JSONObject cannot be converted to JSONArray
JSON is as follows
{
"temp":296.88,
"feels_like":298.86,
"temp_min":296.88,
"temp_max":296.88,
"pressure":1013,
"humidity":89,
"sea_level":1013,
"grnd_level":986
}
I could get data from this alone
String weatherInfo = jsonObject.getString("weather");
Not from this string Why ?
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
String weatherInfo1 = jsonObject.getString("main");
Log.i("weatherMainContent", weatherInfo1);
Log.i("Weather Details" , weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
Log.i("full " , jsonArray1.toString());
String message = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String main = jsonObject1.getString("main");
String description = jsonObject1.getString("description");
Log.i("Weather side Details" , weatherInfo);
Log.i("temperaturerrr", jsonObject1.getString("temp_min"));
String temp_min = jsonObject1.getString("temp_min");
Log.i("temperature", jsonObject1.getString("temp_min"));
String pressure = jsonObject1.getString("pressure");
if (!main.equals("") && !description.equals("") && !temp_min.equals("")) {
message += main + ":" + description +";" + temp_min + "\r\n";
} else {
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
Log.i("Main", jsonObject1.getString("main"));
Log.i("Description", jsonObject1.getString("temp_min"));
}
if (!message.equals("")) {
resultTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
}
}
Your Json is not an Array, but an Object.
Create a new JSONObject of your Json String.
Then just use the object and use the getDouble("propertyName") method to get the value of the property:
String json = "{\"temp\":296.88,\"feels_like\":298.86,\"temp_min\":296.88,\"temp_max\":296.88,\"pressure\":1013,\"humidity\":89,\"sea_level\":1013,\"grnd_level\":986}";
JSONObject weatherInfo = new JSONObject(json);
double temp = weatherInfo.getDouble("temp");
double feels_like = weatherInfo.getDouble("feels_like");
double temp_min = weatherInfo.getDouble("temp_min");
double temp_max = weatherInfo.getDouble("temp_max");
double pressure = weatherInfo.getDouble("pressure");
double humidity = weatherInfo.getDouble("humidity");
double sea_level = weatherInfo.getDouble("sea_level");
double grnd_level = weatherInfo.getDouble("grnd_level");
System.out.println(temp);
System.out.println(feels_like);
System.out.println(temp_min);
System.out.println(temp_max);
System.out.println(pressure);
System.out.println(humidity);
System.out.println(sea_level);
System.out.println(grnd_level);
If this is your data
"{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200} "
you have to just make some changes in the code to retrieve
String jsonString = "your string";
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("weather");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject weatherObj = jsonArray.getJSONObject(i);
System.out.println(weatherObj);
}
String baseValue = json.getString("base");
Object mainValue = json.get("main");
Object visibilityValue = json.get("visibility");
Object windValue = json.get("wind");
#shivas To retrieve the below json { "main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80} from the source json, kindly check first which property is JSONArray and JSONObject.
Here is the code to retrieve it.
main,wind are JSONObject and weather is a JSONArray.
So assuming sourcejson is the entire JSONObject,
JSONObject main = sourcejson.optJSONObject("main");
System.out.println(main.toString());
JSONObject wind = sourcejson.optJSONObject("wind");
System.out.println(wind.toString());
JSONArray weather = sourcejson.optJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
System.out.println(weatherObj.toString());
}
String base = sourcejson.optString("base");
int visibility = sourcejson.optInt("visibility");
Try this, you will get your data.

JSONObject has value but returns null value

[
{
"valve": "4679",
"selling": "5516",
"bal": "9075.4",
"o id": "37",
"invested": "11122", //<<<<<<<- this value returns null
"aProfit": "1012", //<<<<<<<- this value returns null
"count": "182", //<<<<<<<- this value returns null
"cost": "5051" //<<<<<<<- this value returns null
}
]
.- The JSONObject above requested from onPostExecute
#Override
protected void onPostExecute (String ANSWER)
{ String u_id;
try{
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); )
{
JSONObject JO = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
CASH = (String) jsonObject.getString("bal");
USER_VALUE = (String) jsonObject.getString("valve");
INVEST = (String) jsonObject.getString("invested");
PROFIT = (String) jsonObject.getString("aProfit");
COST_P = (String) jsonObject.getString("cost");
COUNT = (String) jsonObject.getString("count");
DashBoard.mprofit.setText(PROFIT);
DashBoard.minvest.setText(INVEST);
DashBoard.massets.setText(COST_P);
DashBoard.mvalue.setText(USER_VALUE); //<<<<<<<- this value returns the value.
Many others do, but some just refused to return and when I cross-check with postman, they all return.
so am now confused because if I swap the places of the valve and the count in the webservices code, it is no more null and vice versa.
Short question: can someone please explain why some values return null in the java coding.
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
//jsonObject = jsonArray.getJSONObject(i); **remove this line thne check remove this line thne check**
String CASH = (String) jsonObject.getString("bal");
String USER_VALUE = (String) jsonObject.getString("valve");
String INVEST = (String) jsonObject.getString("invested");
String PROFIT = (String) jsonObject.getString("aProfit");
String COST_P = (String) jsonObject.getString("cost");
String COUNT = (String) jsonObject.getString("count");
}
}catch (Exception e){
}
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
String CASH = (String) jsonObject.getString("bal");
String USER_VALUE = (String) jsonObject.getString("valve");
String INVEST = (String) jsonObject.getString("invested");
String PROFIT = (String) jsonObject.getString("aProfit");
String COST_P = (String) jsonObject.getString("cost");
String COUNT = (String) jsonObject.getString("count");
}
}catch (Exception e){
}
Try to use this code:
try {
JSONArray jsonArray = null;
jsonArray = new JSONArray(ANSWER);
for (int i = 0; i < jsonArray.length(); ) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
jsonObject = jsonArray.getJSONObject(i);
String valve = (String) jsonObject.getString("valve");
String selling = (String) jsonObject.getString("selling");
String bal = (String) jsonObject.getString("bal");
String o_id = (String) jsonObject.getString("o_id");
String invested = (String) jsonObject.getString("invested");
String aProfit = (String) jsonObject.getString("aProfit");
String count = (String) jsonObject.getString("count");
String cost = (String) jsonObject.getString("cost");
}
}catch (Exception e){
}
Hope this helps...
Happy Coding :)

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

how to access jsonarray elemennts

#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.

Why am I getting duplicates when combining multiple ArrayLists?

Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.

Categories