i have a json-file called "user.json". Now i want to add a new user. I know how to get the content of the file and put it in a String, but i dont know how to add new content correctly. "jsonString" is the content of "user.json"
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
The output is:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
But it should be:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
Does somebody know how to do it right?
I looked it up but all the examples are not working for me, because when i try
JSONObject object = new JSONObject(jsonString);
or
JSONArray array = new JSONArray(jsonString);
i always get "the constructor ist undefined".
Edit:
content of user.json
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:
I solved the problem
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
it seems you are adding fields to your jsonObject, and what you want to do it basically adding the new object to the inner json array (in this case field is called "user"
try this:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
you can use fromObject() method:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);
Related
I am trying to Parse below JSON data to String in Java using (GSON) Library, I am able to parse all JSON fields data except one of the JSON Array. I want to check if it's null/empty then in String variable store null value, if it's not then store the original value.
Input JSON Data:
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": []
}
}
}
]
}
Code that I have done so far,
JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray("issues");
for(int i=0; i<issuesArray.size(); i++) {
JsonObject currentissues = (JsonObject) issuesArray.get(i);
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray= customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.getAsString() : "NULL";
}
However when I execute code I get below error on line :JsonObject customfield
java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject
[![UpdatedCode StackTrace][1]][1]
[1]: https://i.stack.imgur.com/2wY0S.jpg
you dont need to explicitly , cast JsonElement to JsonObject instead use getAsJsonArray , Once you get your array, you can iterate through all the elements of it.
You also need to handle null check for completedCyclesArray before checking its siz else it will give you the NPE , I have fixed that as well.
Please find the modified working code as below
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonResponse).getAsJsonArray();
for(JsonElement e : array) {
JsonObject currentissues = (JsonObject) e;
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray= customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (null != completedCyclesArray && completedCyclesArray.size() > 0) ? completedCyclesArray.getAsString() : "NULL";
}
}
Please find my working solution for the updated json request(which not an array but nested json request)
JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray("issues");
String expand = object.get("expand").toString();
String startAt = object.get("startAt").toString();
String maxResults = object.get("maxResults").toString();
String total = object.get("total").toString();
System.out.println(String.format("expand %s , startAt %s, maxResults %s, total %s", expand, startAt, maxResults, total));
IntStream.range(0, issuesArray.size()).mapToObj(i -> (JsonObject) issuesArray.get(i)).forEach(currentissues -> {
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray = customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.toString() : "NULL";
System.out.println(String.format("Issue_Id %s , Issue_Key %s, Issue_Type %s, Issue_FirstResponseStartTime %s", Issue_Id, Issue_Key, Issue_Type, Issue_FirstResponseStartTime));
});
and this is the output I got :
expand "schema,names" , startAt 0, maxResults 50, total 37875 Issue_Id
1190 , Issue_Key GDS-81, Issue_Type Service Request with Approvals,
Issue_FirstResponseStartTime NULL
Please see my complete working code here complete code
for both the secnarios
Empty completedCycles
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": []
}
}
}
]
}
Non Empty completedCycles
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": [{"name":"abc"},{"name": "xyz"}]
}
}
}
]
}
Try adding getAsJsonObject() at the end of that statement.
I am trying to parse a large json file which contains a bunch of cities (the following is the first two cities in the file):
[
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}
},
{
"id": 519188,
"name": "Novinki",
"country": "RU",
"coord": {
"lon": 37.666668,
"lat": 55.683334
}
} ]
I want to get the IDs of cities whose "name" value matches a String:
JsonParser parser = new JsonParser();
JsonElement jsontree = parser.parse(new FileReader("C:/Users/kevin/Eclipse-workspace-new/kevinzhou_CSCI201_assignment3/WebContent/city.list.json"));
JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = je.getAsJsonArray();
for (Object o : ja)
{
JsonObject city = (JsonObject) o;
if(cityName == city.get("name").getAsString())
{
System.out.println(city.get("id").getAsString());
}
}
However, I am getting the following error : java.lang.IllegalStateException: Not a JSON Object:
and then it spits out the entire file after the colon.
change to
// JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = jsontree.getAsJsonArray();
as it contains an Array at the top level
Try below given code to handle both condition
if (jsontree instanceof JsonObject) {
JsonObject jobject = new JsonObject(jsontree .getAsJsonObject());
} else if (jsontree instanceof JsonArray) {
JsonArray jarray = new JsonArray(jsontree .getAsJsonArray());
}
How can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));
I have this JSON object that I've created using GSON:
{
"data": {
"isDeleted": false,
"period": 201601,
"columnMap": {
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
But my requirement is for it to look like
{
"data": {
"isDeleted": false,
"period": 201601,
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
How do I solve this, because all the values in "columnMap" are generated dynamically.
You need to create instance updateJsonObj of JsonObject to update key and value of columnMap using for each loop. Following code snippet is the solution :
String json = "{ \"data\": {\"isDeleted\": false,\"period\": 201601,"
+ "\"columnMap\": {\"1c49eb80-7b53-11e6-bc4b-afbeabb62718\": \"5000\","
+ "\"1c49eb80-7b52-11e6-bc4b-afbeabb62718\": \"hello\","
+ "\"03a534c0-a7f1-11e6-9cde-493bf5c47f4\": \"AUS\", "
+ "\"03a534c0-a7fa-11e6-9cde-493bf5c47f4\": \"123\"}}}";
Gson gson = new Gson();
JsonObject root = new JsonParser().parse(json).getAsJsonObject();
JsonElement dataElement = root.get("data");
// cobj has value of colummMap of json data
JsonObject cobj = (JsonObject) root.get("data").getAsJsonObject().get("columnMap");
JsonObject updateJsonObj = root;
// remove columnMap node as you wanted !
updateJsonObj.get("data").getAsJsonObject().remove("columnMap");
for (Entry<String, JsonElement> e : cobj.entrySet()) {
//update updateJsonObj root node with key and value of columnMap
updateJsonObj.get("data").getAsJsonObject().addProperty(e.getKey(), e.getValue().getAsString());
}
String updateJson = gson.toJson(updateJsonObj);
System.out.println(updateJson);
I have a json file like this
[ {
"id":"serve-coffee",
"tags":[ {
"name": "#tag1", "line": 1
}
],
"description":"Coffee should not be served\n",
"name":"Serve coffee",
"keyword":"Feature",
"line":2,
"elements":[ {
"id": "serve-coffee;buy-last-coffee", "tags":[ {
"name": "#tag2", "line": 6
}
],
"description":"",
"name":"Buy last coffee",
"keyword":"Scenario",
"line":7,
"steps":[ {
"name": "there are 1 coffees left in the machine", "keyword": "Given ", "line": 8
}
,
{
"name": "I have deposited 1$", "keyword": "And ", "line": 9
}
],
"type":"scenario"
}
],
"uri":"src\/test\/resources\/traffic-remove-locations.feature"
}
]
Iam trying to convert the above json file to JSONObject.But am getting class cast exception "java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
code
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
// Read from File to String
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object object = parser.parse(new FileReader(fileName));
jsonObject = (JSONObject) object; // Getting classCast Exception here.
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
but when i changed the line jsonObject = (JSONObject) object; to JSONArray jsonArray = (JSONObject)object the exception disappears.
But if am casting to JSONArray then how can i get the values like id,tags and description from JSONArray.
please provide a suggestion guys
Your JSON file represents an array with one object in it. So if that were a Java data structure, you're effectively doing this:
int[] arr = {5};
int i = (int)arr;
This obviously doesn't work because you can't cast an array to a singular object. What you actually want to do it pull out the first element of the array. To continue the Java example, you want to do
int[] arr = {5};
int i = (int)arr[0];
With the JSON stuff, your parser.parse() call returns a JSONArray, not a JSONObject. So you'll need to do something like this:
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
JSONArray array = (JSONArray) parser.parse(new FileReader(fileName));
jsonObject = array.getJsonObject(0);
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
Try casting to JsonArray and then cast access the objects one by one with help of the index from the JSON array.
Object object = parser.parse(new FileReader(fileName));
JsonArray jsonArr = (JsonArray) object; // Getting c
jsonObject jsonObj = jsonArr.get(0); //use index to access like a list
I was also facing the same issue. I did the below changes to make it work.
Below is my sample JSON.
{
"routes": [{
"startTime": 1520319414,
"routeInfo": [{
"routePart": 0,
"transType": "WALK",
"transDetails": {
"startLoc": {
"lat": 28.6434862,
"lon": 77.22542659999999
}
}
}, {
"routePart": 1,
"transType": "BUS",
"transDetails": {
"routeNumber": "307-U",
"interStopDetails": [{
"seq": 1,
"name": "test1",
"loc": {
"lat": 28.64302,
"lon": 77.2260367
},
"eta": 1520319600
}
]
}
}
],
"totalTime": 5742
}
]
}
Solution to Parse:
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(FilepathDummy));
JSONArray jsonRoutes= (JSONArray) obj.get("routes"); //Gives Main JSoN
JSONObject routeJsonObject = (JSONObject) jsonRoutes.get(0); // Route Array into JSON
JSONArray routeInfoArray = (JSONArray) routeJsonObject.get("routeInfo"); // RouteInfo Array
Hope this solve your problem.