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"
}
}
]
}
Related
I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.
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);
I have a problem with convert string to json.
Namely, my json string is:
{"serverId":2,"deviceId":736,"analysisDate":"2017-05-11T07:20:27.713Z","eventType":"Logs","eventAttributes":[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]}
My code:
try {
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray("eventAttributes");
System.out.println("ARRAY: " + array);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = new JSONObject(array.getJSONObject(i));
System.out.println("OBJ: " + obj);
}
} catch (JSONException ex) {
Exceptions.printStackTrace(ex);
}
System.out.println array is:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
but if I print obj is "{}", four times. So it is correct, because array has 4 elements, but why it is empty object? I'm using org.json.
Thanks
array.getJSONObject(i) is already returning you an object of type JSONObject you dont need to pass it to constructor of JSONObject class.
simply write
...
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println("OBJ: " + obj);
}
...
You're calling the JSONObject(Object) constructor, passing in a JSONObject (the element in the array). That constructor is documented as:
Construct a JSONObject from an Object using bean getters. It reflects on
all of the public methods of the object. For each of the methods with no
parameters and a name starting with "get" or
"is" followed by an uppercase letter, the method is invoked,
and a key and the value returned from the getter method are put into the
new JSONObject. [...]
Now JSONObject itself doesn't have anything that fits a bean getter, so you end up with no keys. You don't want to treat the JSONObject as a bean.
That's why your current code doesn't work. To fix it, just don't call the constructor - instead, use the fact that the array element is already a JSONObject:
JSONObject obj = array.getJSONObject(i);
Output with that change:
OBJ: {"name":"level","value":"INFO"}
OBJ: {"name":"type","value":"Video Blocked On"}
OBJ: {"name":"cameraId","value":"722"}
OBJ: {"name":"userId","value":"1"}
If you consider following example you can do it in 3 ways :
jsonString = {
"name" : "John",
"sport" : "Soccer",
"age" : 25,
"id" : 100,
"score" : [ 2, 1, 4, 5, 0, 1, 2, 3, 1]
}
String to JSON Object using GSON
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert Java object to JSON by using method toJson()
String str = g.toJson(p);
JSON String to Java object using JSON-Simple
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
String to JSON - Jackson Example
Player john = new ObjectMapper().readValue(jsonString, Player.class);
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
I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data
I used following java code for that but it's not giving me the result I need, please someone help me...
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("content");
Iterator<String> iterator = msg.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Sample JSON
{
"status": 200,
"message": "ok",
"timestamp": "2014-05-22T14:29:56.824+03:00",
"pagesCount": 1,
"version": "1.1",
"pages": [
{
"number": 100,
"subpages": [
{
"number": 1,
"timestamp": "2014-05-22T13:41:41.116+03:00",
"content": "text"
},
Something like this perhaps?
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
for (Object p : pages) {
JSONObject page = (JSONObject) p;
JSONArray subPages = (JSONArray) page.get("subpages");
if (subPages != null) {
for (Object sp : subPages) {
JSONObject subPage = (JSONObject) sp;
System.err.println(subPage.get("content"));
}
}
}
}
You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. In addition, the only field named content has a string as its value and not a JSON array.
To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");
// Page 10
JSONObject page = (JSONObject) pages.get(10);
// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");
// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);
// Content of subpage 7 of page 10
String content = (String) subpage.get("content");
Please note that I am assuming that e.g. index 10 corresponds to page 10. That may not be true in your case; pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need.
In any case, if you are indeed using json-simple, as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList. Therefore, their interfaces should be quite familiar to you.
Disclaimer: Untested code - exception and other error handling removed for brevity
First of all, The json is not valid (if you pasted it complete)
In JSON "{}" is an object, and "[]" is an array, others are just key value pairs.
Simply you can do like this without using parser ,
JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
//fetch other
JSONObject objJSON = pages.getJSONObject(count);
JSONArray subpages = objJSON.getJSONArray("subpages");
for(int count1 = 0; count1 < subpages.length(); count1++){
JSONObject objSubpageJSON = subpages.getJSONObject(count1);
//fetch other
int number = (int) objSubpageJSON.getInt("number");
}
}