I need to read the output of a BufferedReader object which is in json format, parse the json and extract some values. My code looks as below:
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc1.getInputStream()));
Stream<String> s = reader.lines();
Object[] t = s.toArray();
String result = Arrays.toString(t);
JSONParser jp = new JSONParser();
JSONArray jArr = (JSONArray) jp.parse(result);
System.out.println(jArr);
The JSONArray jArr looks as below:
[
{
"result": {
"totalSize": 1,
"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
],
"done": true
},
"status": 0
}
]
I need to get the properties of "records". I have the subsequent code working, just need to create a json object with the values inside "records". Output json object required is:
{"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
I am facing json array and json object incompatibility issues while trying to case jArr as json object. Can someone suggest a way to do this
Join the stream as a single String. Use try-with-resources so the BufferedReader gets closed.
String result;
try (Stream<String> stream = reader.lines()) {
result = stream.collect(Collectors.joining());
}
Related
I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.
This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.
1.
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
The JSON the ID I need to access has a comment next to it:
"data": [
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"$state": "save",
"$process_flow": false,
"Street": "95## ### ######",
"id": "**3461487000073355176**", ----This is the ID I need -----
"Coverage_A_Dwelling": 100000,
"$approval": {
"delegate": false,
"approve": false,
"reject": false,
"resubmit": false
},
"Created_Time": "2020-12-10T09:05:17-05:00",
"Property_Details": "Primary Residence",
"Created_By": {
"name": "My name",
"id": "346148700000017",
"email": "m#gmail.com"
},
"Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
"$review_process": {
"approve": false,
"reject": false,
"resubmit": false
},
"Property_State": "FL",
"Property_Street": "95",
"Roof_Material": "Asphalt Shingle",
"Full_Name": "Clare Em",
"Property_City": "Land ",
"Email_Opt_Out": false,
"Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
"Insured_1_DOB": "1942-02-20",
"$orchestration": false,
"Tag": [],
"Email": "cr#yahoo.com",
"$currency_symbol": "$",
"$converted": false,
"Zip_Code": "338",
"$approved": true,
"$editable": true,
"City": "Land O Lakes",
"State": "FL",
"Structure_Type": "Single Family",
"Prior_Carrier": {
"name": "Default Carrier (DO NOT DELETE OR CHANGE)",
"id": "3461487000000235093"
},
"Source": {
"name": "EverQ",
"id": "346148700006474"
},
"First_Name": "Clarence",
"Modified_By": {
"name": "My name",
"id": "3461487000000172021",
"email": "m#gmail.com"
},
"Phone": "7036159075",
"Modified_Time": "2020-12-10T09:05:17-05:00",
"$converted_detail": {},
"Last_Name": "####",
"$in_merge": false,
"$approval_state": "approved",
"Property_Zip": "34638"
}
],
"info": {
"per_page": 200,
"count": 1,
"page": 1,
"more_records": false
}
}
If I understood it correctly, you can get the id like this:
Here, json has the following value.
[
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"id": "**3461487000073355176**"
...
}
]
Now I can iterate over JSONArray to get the id.
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String id = (String) jsonObject.get("id");
System.out.println(id);
}
It prints out **3461487000073355176**.
You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.
The posted JSON response is missing the initial "{".
Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):
// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?
For example, defining something like this:
#Getter #Setter
// This models the response string from body
public class Response {
#Getter #Setter
// This models objects in the data list/array
public static class IdHolder {
// Only id because not interested of the rest
private String id;
}
// Only list of id holders because not interested of the rest
private List<IdHolder> data;
}
Then it would be as easy as:
Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);
I am learning to work with json files and I'm using the JSON-java library from https://github.com/stleary/JSON-java
I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
You are almost there, all you have to do is to new a JSON array from jsonToken as follows:
BTW, I think the JSON library you are using is org.json, not JSON.ORG. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.
Today I started writing a simple parser for a log file. I want to take the log file and transform it into a simple json structure.
The log file is consistent and has 3 main parts (example below):
the timestamp [23 digits]
the code [4 digits]
the payload [variable digits]
Example log
2018-07-25T08:47:16,094,164f,test1
2018-07-25T08:47:18,163,1678,test2
2018-07-25T08:47:19,501,1662,test3
2018-07-25T08:47:21,278,1634,test4
2018-07-25T08:47:23,347,1632,test5
2018-07-25T08:47:24,686,1665,test6
2018-07-25T08:47:26,463,1678,test7
2018-07-25T08:47:28,533,1678,test8
2018-07-25T08:47:29,877,1632,test9
2018-07-25T08:47:31,687,1632,test10
From this I wanted to create a JSON file that would incorporate well the information inside. This is what I came up with (using org.json.JSONObject library).
BufferedReader reader = new BufferedReader(new FileReader ("file.log"));
String line = null;
String timestamp = null;
String eventCode = null;
String payload = null;
JSONObject codePayload = new JSONObject();
JSONObject finalString = new JSONObject();
for (int i = 0; i < 10; i++) {
line = reader.readLine();
timestamp = line.substring(0, 23);
eventCode = line.substring(24, 28);
payload = line.substring(29, line.length());
codePayload.put("ID", eventCode);
codePayload.put("PL", payload);
finalString.put(timestamp, codePayload);
codePayload = new JSONObject();
}
System.out.println(finalString.toString());
This little snippet should work quite well (don't mind the for) and it kinda does. It creates the JSON file according to the string I give it but it puts then in a strange order, see below.
{
"2018-07-25T08:47:24,686": {
"ID": "1665",
"PL": "test6"
},
"2018-07-25T08:47:29,877": {
"ID": "1632",
"PL": "test9"
},
"2018-07-25T08:47:31,687": {
"ID": "1632",
"PL": "test10"
},
"2018-07-25T08:47:16,094": {
"ID": "164f",
"PL": "test1"
},
"2018-07-25T08:47:21,278": {
"ID": "1634",
"PL": "test4"
},
"2018-07-25T08:47:18,163": {
"ID": "1678",
"PL": "test2"
},
"2018-07-25T08:47:23,347": {
"ID": "1632",
"PL": "test5"
},
"2018-07-25T08:47:28,533": {
"ID": "1678",
"PL": "test8"
},
"2018-07-25T08:47:19,501": {
"ID": "1662",
"PL": "test3"
},
"2018-07-25T08:47:26,463": {
"ID": "1678",
"PL": "test7"
}
}
As you can clearly see it places the objects in the wrong order and I really don't know why. If someone has the slightest idea on how this problem could occur please comment below. Thanks a lot!
The org.json.JSONObject is un-ordered, so better to use javax.json.JSONObject OR if you are using org.json library, use the org.json.JSONArray to store the timestamps in order.
I am trying to use JsonObject to convert the java object to String. Following is the code that i am using to add the properties :
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", favoriteWrapper.getId());
jsonObject.addProperty("menuitemid", favoriteWrapper.getMenuItemId());
jsonObject.addProperty("displayname", favoriteWrapper.getDisplayName());
jsonObject.addProperty("description", favoriteWrapper.getDescription());
jsonObject.addProperty("alias", favoriteWrapper.getAlias());
Gson gson = new Gson();
jsonObject.addProperty("condiments", gson.toJson(favoriteWrapper.getCondiments()));
Here the last property condiments is a list of Long values and following is the response retrieved:
[
{
"id": 1,
"menuitemid": 1,
"displayname": "Ham",
"description": "Ham",
"alias": "Ham",
"condiments": "[1,8,34,2,6]"
}
]
Expected output is as following which is different for condiments:
[
{
"id": 1,
"menuitemid": 1,
"displayname": "Ham",
"description": "Ham",
"alias": "Ham",
"condiments": [1,8,34,2,6]
}
]
What should I do to get the condiments as JSON array rather than String ?
I found the answer to my problem. I used JsonArray and JsonPrimitive to achieve the required response:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", favoriteWrapper.getId());
jsonObject.addProperty("menuitemid", favoriteWrapper.getMenuItemId());
jsonObject.addProperty("displayname", favoriteWrapper.getDisplayName());
jsonObject.addProperty("description", favoriteWrapper.getDescription());
jsonObject.addProperty("alias", favoriteWrapper.getAlias());
JsonArray condiments = new JsonArray();
for (Long condimentId : favoriteWrapper.getCondiments()) {
condiments.add(new JsonPrimitive(condimentId));
}
jsonObject.add("condiments", condiments);
jsonObjects.add(jsonObject);