Getting string from JSON response in Java - java

Can't figure out how to get string of JSON response. From OpenWeatherMap API ( https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22 ) want to get the first temp_min and temp_max.
I have tried to post the JSON response in a JSON formatter and go through it logically but that didn't help me much. Tried different solutions throughout google.
The last try from my side is this:
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("list");
JSONObject firstObject = (JSONObject)array.get(0);
String tempmax = firstObject.getJSONObject("main").getString("temp_max");
String tempmin = firstObject.getJSONObject("main").getString("temp_min");
From the following API response, I want to receive temp_min and temp_max:
{
"cod":"200",
"message":0.0032,
"cnt":36,
"list":[
{
"dt":1487246400,
"main":{
"temp":286.67,
"temp_min":281.556,
"temp_max":286.67,
"pressure":972.73,
"sea_level":1046.46,
"grnd_level":972.73,
"humidity":75,
"temp_kf":5.11
},
"weather":[ ],
"clouds":{ },
"wind":{ },
"sys":{ },
"dt_txt":"2017-02-16 12:00:00"
},
[..]
I expect to get the temp_min and temp_max values from API response, but at the moment it's just empty.

I have just checked your code using this library with newest version. I loaded json content from local file and I had to change the way you read values of temperature :
public static void main(String[] args) throws IOException {
String collect = Files.lines(Paths.get("src/main/resources/waether.json")).collect(Collectors.joining());
JSONObject jsonObject = new JSONObject(collect);
JSONArray array = jsonObject.getJSONArray("list");
JSONObject firstObject = (JSONObject)array.get(0);
double tempmax = firstObject.getJSONObject("main").getDouble("temp_max");
double tempmin = firstObject.getJSONObject("main").getDouble("temp_min");
System.out.println("Temp min " + tempmin);
System.out.println("Temp max " + tempmax);
}
The output is :
Temp min 259.086
Temp max 261.45
As you see I had to use getDouble methods as those values were not json strings - they were numbers. I am not sure which version of this library you are using but with newest version it works.

Big thanks to michalk and others for help. Edited michalk's answer a bit, so it meets my project and it solved the problem I was having.

Related

What is the best way to concat two JSONObject with same key in a JSONArray

The JSON request i get from the server side is a compressed format, since data is too large , it has been splitted to two json object in the NextData JSONarray , how can i combine these two objects before i can decompress and get the values . Iam not able to achieve this, any ideas would be appreciated. Thanku.
"NextData": [
{
"Element": "KgYAAB+LCAAAAAAABACNZhHeKQVHiY8voyqMuQhFrakNHzb9/eiuGCeRrghvPrzll+2WzXX15f2OkTTQ/bIz3j308fjXhPqLD"
},
{
"Element": "u5Ot3i2FwO6KguNo7iqUhY/PitP7y+DA/HvbllSj8C+t04gzgTHrkJPVRD/w/i3wBGYBj6x2Ienh+s1Xr0/U+6LEfhKgYAAA=="
}
],
The following function gets the root array and returns the concatenation of all elements inside of it.
public String concat(JSONArray data) {
String response = "";
for (int i = 0; i < data.length(); i++)
response += data.optJSONObject(i).optString("Element"));
return response;
}

reading data from nested JSON Object using java

i am struggling with reading some values from JSON object which i get it when i hit REST API..
MY GOAL: i need to iterate over each set of data inside data object array check the value of TRAN_ID and take action accordingly.
below is the format of data
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]"
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": "[{TRAN_IND:current},{TRAN_TYP:Debit},{country:US}]"
}
]
}
it looks easy and i have tried multiple solutions out there on internet but i dont know it doesnt work for me and i get below error while reading "PARAMS" and converting it to JSONArray for further processing
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
What i have tried:
private static void jsonParser(String jsonStr) throws ParseException {
JSONObject data= (JSONObject)JSONValue.parse(jsonStr );
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
String tran_ind=(String) servParam.get(0);
System.out.println( tran_ind);
}
I'm guessing this is what you what?
try{
JSONObject obj = new JSONObject(sample);
JSONArray data = obj.getJSONArray("data");
for(int i=0; i<data.length(); i++){
JSONObject detail = data.getJSONObject(i);
detail.getString("CUST_ID"); //here is the customer id
detail.getString("EXPRY_DATE"); //here is the exp date
JSONArray params = detail.getJSONArray("PARAMS");
for(int j=0; j<params.length(); j++){
// {TRAN_IND:current},{TRAN_TYP:Debit},{country:US}
JSONObject res = params.getJSONObject(j);
String tran_ind = res.toString();
String tran_type = res.toString();
String country = res.toString();
out.println(tran_ind + " " +tran_type + " " + country);
}
}
}catch (JSONException ex){
ex.printStackTrace();
}
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
=> Because you are trying to parse String value "[{TRAN_IND:savings},{TRAN_TYP:Debit},{country:US}]" into the JsonArray by code:
JSONArray servParam= (JSONArray) JsonRow.get("PARAMS");
Params seems to be a String, actually.
Don't write your own parser. If you only need to read that string in each element of the array, I would simply cast the whole JSON to a Map with Jackson:
HashMap<String,Object> parsed =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
and then iterate over the "data" element (which would be a list of maps).
List<Map> data = (List) parsed.get("data");
The real problem is that those are not nested JSON strings. That would be
"PARAMS": "[{\"TRAN_IND\":\"current\"},{\"TRAN_TYP\":\"Debit\"},{\"country\":\"US\"}]"
so "text" parts are surrounded by "-s inside (which have to be escaped as \"-s).
In that case you could write
String json=
"{\n"+
" \"data\": [\n"+
" {\n"+
" \"CUST_ID\": \"CUST7\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"savings\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" },\n"+
" {\n"+
" \"CUST_ID\": \"CUST8\",\n"+
" \"EXPRY_DATE\": null,\n"+
" \"PARAMS\": \"[{\\\"TRAN_IND\\\":\\\"current\\\"},{\\\"TRAN_TYP\\\":\\\"Debit\\\"},{\\\"country\\\":\\\"US\\\"}]\"\n"+
" }\n"+
" ]\n"+
"}";
// Print input for clarity:
System.out.println(json);
JSONObject data= (JSONObject)JSONValue.parse(json);
JSONArray jsonObj = (JSONArray)data.get("data");
JSONObject JsonRow = (JSONObject)jsonObj.get(0);
// parse nested JSON
JSONArray servParam= (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS"));
// array element is an object ({"TRAN_IND":"savings"}), so toString has to be used:
String tran_ind=servParam.get(0).toString();
System.out.println(tran_ind);
(The backslash-heaps are there because double-quotes had to be escaped in source code, and also the suggested escaped double quotes. So they would not appear in a JSON file. Try the code in action, it prints the JSON it works on)
So (JSONArray)JSONValue.parse((String)JsonRow.get("PARAMS")) would get and parse the nested JSON.
But now you either have to rework the code what generates your input, or parse the nested non-JSON manually.
You can use below code for parsing.
String servParam = (String) JsonRow.get("PARAMS");
String servParamSplitted[] = servParam.substring(1, servParam.length() - 1).split(",");
String traind_id[] = servParamSplitted[0].substring(1, servParamSplitted[0].length() - 1).split(":");
String train_id=traind_id[1];
I like to add that your JSON should be like below format.
{
"data": [
{
"CUST_ID": "CUST7",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"savings"},{"TRAN_TYP":"Debit"},{"country":"US"}]
},
{
"CUST_ID": "CUST8",
"EXPRY_DATE": null,
"PARAMS": [{"TRAN_IND":"current"},{"TRAN_TYP":"Debit"},{"country":"US"}]
}
]
}
So, we can parse it using below code.
JSONArray servParam = (JSONArray) JsonRow.get("PARAMS");
JSONObject jsonObjectTrainID = (JSONObject) servParam.get(0);
String TrainIDValue = (String) jsonObjectTrainID.get("TRAN_IND");

how to read JsonElement ? "This is not a JSON Array."

I have JsonElement like this:
{
"76800769": {
"prosjekLat": 45.784661646364,
"prosjekLong": 15.947804310909,
"brojCelija": 11
},
"76800772": {
"prosjekLat": 45.7847808175,
"prosjekLong": 15.9477082775,
"brojCelija": 4
},
"2946694": {
"prosjekLat": 45.78475167,
"prosjekLong": 15.9475975,
"brojCelija": 1
},
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
}
I also create Model:
public class AddMarker {
int cellId;
double longitude;
double latitude;
}
I want to read JSON file and put values to List<AddMarker>.
I'm trying with this:
JsonElement data = response.body();
JsonObject obj = data.getAsJsonObject();
JsonArray arr = obj.getAsJsonArray();
but I'm getting an err: "This is not a JSON Array."
Your JSON is not an array.
Json Array syntax dictates that in order to have an array, your object must be formatted as:
[
{
...
},
{
...
},
...
{
...
}
]
Right now you have the outer square brackets ([]) as curly braces ({}). Change it to square brackets and your code should run correctly.
You're trying to make a array from a single object: JsonArray arr = obj.getAsJsonArray(), where obj is for exemple just this :
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
you need to get the body from the response and make an array with all these objects, not from a single one
You can use this:
JsonObject json = new JsonObject(data);
String str1 = json.getString("76800769");
JsonObject json2 = new JsonObject(str1);
float str11 = json2.getFloat("prosjekLat");
Using org.json liberary, you can read the element as follows:
JSONObject obj = new JSONObject("your json element");
JSONObject obj2 = (JSONObject) obj.get("76800769");
System.out.println(obj2.get("brojCelija"));
System.out.println(obj2.get("prosjekLat"));
System.out.println(obj2.get("prosjekLong"));
which gives below output:
11
45.784661646364
15.947804310909
I need to convert JSON Object to array. In php just use array_values( $json ).
I solve my problem using this:
json_encode(array_values($izracunatProsjek), true);

Unable to get json parsing for specific field name

I am working on Yahoo Finance. Trying to parse json data from a url, such as Google finance data.
I am fetching data into a string "str" and then parsing the json data to reach the name field inside resources.
the json data is :
{
"list":{
"meta":{
"type":"resource-list",
"start":0,
"count":1
},
"resources":[
{
"resource":{
"classname":"Quote",
"fields":{
"name":"Alphabet Inc.",
"price":"710.489990",
"symbol":"GOOGL",
"ts":"1452891600",
"type":"equity",
"utctime":"2016-01-15T21:00:00+0000",
"volume":"3833751"
}
}
}
]
}
}
I am trying to use this code, but it is not working - need to reach the "name" field:
str4 = Client.execute(httpget, responseHandler);
//str holds the json data given above- checked.
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resorces");
JSONObject fields = resources.getJSONObject(1);
str2 = fields.getString("name");
I notices three issues with your code:
you have one item in your JSONArray, so you should retrieve item 0, not item 1.
you misspelled the word resources in your code.
Also, I think you didn't retrieve the fields correctly. This should do it:
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
JSONObject fields = resources.getJSONObject(0).getJSONObject("resource").getJSONObject("fields");
str2 = fields.getString("name");

Extract different values returned in json format using GET REST call

I am developing an application in which I am using GET REST call to get some specific nodes which return's me the nodes in the below json format:
[
{
"nodeId": "30",
"datasetId": "2",
"localId": "30",
"datasetName": "Optimal Travel Route",
"nodeName": "Location30",
"nodeDesc": "Find the optimal travel route using travelling salesman problem ",
"nodeStatus": "Private",
"gpsLat": "8.233240",
"gpsLong": "15.029300",
"addedBy": "internIITD",
"addedOn": "2012-06-29 11:08:28",
"updatedOn": "2012-06-29 11:08:28"
}
]
they are no newlines .I have added here to make it readable. I am doing this to convert it to string.:
BufferedReader in = new BufferedReader(new InputStreamReader(
httpCon.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
System.out.println(inputLine);
}
String Result;
Result=sb.toString();
System.out.println("result:"+Result);
I want to extract the longitude and latitude of the nodes that will be given meeting specific requirements. I am working in NetBeans 7.1.2 . I am new to JAVA.
So , can anyone tell is there any way to extract this latitude and longitde information and store it in integer varibles.
I used to declare JSONObject but it is not working here .I don't know why?I am not able to use JSONArray or JSONObect in my code. It is showing me an error.In the class in which I am doing this does not have a mail function. this class i.e. file has been called by some other .java file . I have multiple windows in my application.
Please help.
This would be a solution:
String jsonSource = /* your json string */;
JSONArray array = new JSONArray(jsonSource);
for (int i = 0; i < array.length(); i++) {
JSONObject firstObject = (JSONObject) array.get(i);
System.out.println("Lat is: " + firstObject.getDouble("gpsLat"));
System.out.println("Long is: " + firstObject.getDouble("gpsLong"));
}
This would print:
Lat is: 8.23324
Long is: 15.0293
The outermost characters in that string are square brackets, so you're not dealing with a JSON object, you have a JSON array.
You said you've used JSONObject in other situations. JSONObject is for objects (which start with a {). Since what you have here is an array, you want to use JSONArray instead.
After creating a JSONArray from this string, calling getJSONObject(0) on it would get you a JSONObject for the array's first element (which is what actually contains the data in the example you've posted). Assuming the structure you posted, you'd need to do something like this:
JSONArray outerArray = new JSONArray(Result);
JSONObject nodeObject = outerArray.getJSONObject(0);
After that you can work with nodeObject like any other JSONObject.

Categories