I want to have a java list for all elements which are in the "in" or "out" element.
My json string:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"},
{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}:""
Until now I did this way:
String message = json.findPath("in").textValue();
But this way can only access to the first hierarchy.
My json example show two elements in the "in" element. How I can get a list of these internal "in" elements?
You could use the library JSONSimple in order to parse your JSON data by this code:
JSONParser parser = new JSONParser();
JSONObject o = (JSONObject) parser.parse(yourJsonAsString);
JSONArray ins = (JSONArray) o.get("in");
JSONArray outs = (JSONArray) o.get("out");
String firstIpAddress = ((JSONObject) ins.get(0)).get("ip").toString();
Thank you for your help. I found an other way to find all sub elements.
Json example:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"}
,{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}
My solution:
JsonNode json = request().body().asJson();
Logger.info("JSON : " + json.findPath("in").findPath("id"));
Logger.info("JSON : " + json.findValues("in"));
List<JsonNode> ins = new org.json.simple.JSONArray();
ins = json.findValues("in");
for (final JsonNode objNode : ins) {
for (final JsonNode element : objNode) {
Logger.info(">>>>>" + element.findPath("id"));
//create my object for database
}
}
Now I can create my Object for the database.
#eztam thank you
Related
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");
I am struggling to fit in a jsonArray inside a json object (through java code).. please help me out.
My Input JsonObject is :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W"
}
}
I will have to read "imageURL" property from this JSONObject and append its variants to the same json object (image variants will be in SortedSet data structure).
Sample O/P 1 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
"http:example.com/imageResource_variant1.jpg",
"http:example.com/imageResource_variant2.jpg"
]
}
}
Sample O/P 2 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
}
}
The logic i tried to get sample output 2 is some what like below,
// productDetail is the give input JSONObject
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
product.append("variants", imageUrlsArray);
When i tried to print the productDetail JSON object after executing above logic
System.out.println(productDetail.toString());
I observed the following output :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
]
}
}
If you notice, It's coming up like Array of arrays (extra [ ] for "variants"),
Please help me in understanding Where my logic is going wrong.
And also, Please help me getting the First sample out put.
Appreciate quick response..
Thanks,
Rohit.
First sample can be archivable as simple as this:
JSONObject product = productDetail.optJSONObject("products");
JSONArray imageUrlsArray = new JSONArray();
imageUrlsArray.put(0, "http:example.com/imageResource_variant1.jpg");
imageUrlsArray.put(1, "http:example.com/imageResource_variant2.jpg");
product.append("variants", imageUrlsArray);
Try using put instead of append:
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
-product.append("variants", imageUrlsArray);
+product.put("variants", imageUrlsArray);
From the docs:
Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.
Im unable to access data from nested objects from the inner elements. This is the json string-
{"created_at":"Tue Jun 14 04:06:55 +0000 2016",
"id":7426,
"id_str":"7425",
"text":"sample",
"user":{"id":529094887,"id_str":"529094887","name":"One Direction Japan","screen_name":"1D_OfficialJP"}
"entities":{"hashtags":[{"text":"ChoiceLoveSong"},{"text":"1DJP"],"media_url":"http:\/\/pbs.twimg.com\/media\/Ck4ijC2UkAA59rU.jpg",]}}
This is my code-
try{ JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsontext);
createdat = (String) jsonObject.get("created_at");
System.out.println(createdat);
twittertext = (String) jsonObject.get("text");
System.out.println(twittertext);
if (jsonObject.get("id")!= null)
id = (long) jsonObject.get("id");
System.out.println(id);
id_str = (String) jsonObject.get("id_str");
System.out.println(id_str);
// loop array
JsonNode json = new ObjectMapper().readTree(jsontext);
JsonNode user_fields = json.get("user");
name = user_fields.get("name").asText();
System.out.println(name);
scrname=user_fields.get("screen_name").asText();
System.out.println(scrname);
JsonNode entities_fields = json.get("entities");
String hashtags = entities_fields.get("hashtags").asText();
System.out.println("hashtags is "+ hashtags);
JSONArray hashtagsContent = (JSONArray) jsonObject.get("hashtags");
Iterator<String> entitiesNames = entities_fields.getFieldNames();
while (entitiesNames.hasNext()) {
System.out.println(entitiesNames.next());
}
jsonObject.get("user_mentions");
}
// followed by catch block ....
Actually im interested in extracting data from inside the hashtag array, specifically i want to store those datas in an array.With the above code im only able to print the keys and not the values of entities object. Also the number of elements in the array may vary
My problem is parsing 2d arrays and to fix the erros. Belowe is my jason file, java code and a list of errors.
This is my Json file:[
{
"elementaryProductId":1,
"bonusMalus":30,
"deductible":500,
"comprehensive":1,
"partial":0,
"legacyPremium":130,
"product":{
"productId":2,
"garage":"true",
"constructionYear":1990,
"region":"East",
"dateOfBirthYoungest":"1983-06-22",
"objectValue":25000,
"type":"Car"
}
},
And this is my java code, i think that the problem is with defining a second array:
try {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator i = jsonArray.iterator();
while (i.hasNext()){
JSONObject object = (JSONObject) i.next();
.
.
.
JSONArray productArray = (JSONArray) jsonParser.parse("product");
Iterator j = productArray.iterator();
while (j.hasNext())
{
JSONObject product = (JSONObject) j.next();
long productId = (Long) product.get("productId");
System.out.println("The id is: " + productId);
}`
List of errors:Unexpected character (p) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at com.domain.project.SveUMain.main(SveUMain.java:66)
It appears the error is coming from this line:
JSONArray productArray = (JSONArray) jsonParser.parse("product");
...
Unexpected character (p) at position 0.
That line of code is going to try to parse the string "product" as if it were a JSON string. It's not, of course, so the parser bails out complaining about the very first character.
If you're trying to access the "product" field of each JSON object, you could do it like this:
Iterator i = jsonArray.iterator();
while (i.hasNext()){
JSONObject object = (JSONObject) i.next();
JSONObject productObj = (JSONObject) object.get("product");
JSON.simple doesn't appear to have a function that would return the product objects from each object in the array with one call.
This json file has a Syntax error.
When you try to validate the file inside an online editor, then it should give you an syntax error on line 1.
A json file starts with an object "{" then inside this you can use your array.
Also the last "," is wrong, because there is no element afterwards. (And you need to close the array "]" and the object "}".
Here are two examples which could be your correct json file.
{
"elementaryProductId":1,
"bonusMalus":30,
"deductible":500,
"comprehensive":1,
"partial":0,
"legacyPremium":130,
"product":{
"productId":2,
"garage":"true",
"constructionYear":1990,
"region":"East",
"dateOfBirthYoungest":"1983-06-22",
"objectValue":25000,
"type":"Car"
}
}
And thats the second solution:
{
"array": [
{
"elementaryProductId": 1,
"bonusMalus": 30,
"deductible": 500,
"comprehensive": 1,
"partial": 0,
"legacyPremium": 130,
"product": {
"productId": 2,
"garage": "true",
"constructionYear": 1990,
"region": "East",
"dateOfBirthYoungest": "1983-06-22",
"objectValue": 25000,
"type": "Car"
}
}
]
}
I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...