JSONObject create Json object issue - java

I trying to create the code which generates the JSON data which should look like this
{
"Main": [
{
"prim": "Hello ",
"secon": [
{
"ads": "A Message"
}
]
}
]
}
The code I am trying with is generating like below
{
"Main": [
{
"prim": "Hello"
},
{
"secon": [
{
"ads": "A Message"
}
]
}
]
}
Code:
JSONObject prim = new JSONObject();
prim.put("prim", Hello");
JSONObject ads = new JSONObject();
ads.put("ads", "A Message");
JSONArray seconArray = new JSONArray();
seconArray.put(ads);
JSONObject secon = new JSONObject();
secon.put("secon", seconArray);
JSONArray Main = new JSONArray();
Main.put(prim);
Main.put(secon);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Main", Main);
JSONArray topJson = new JSONArray();
topJson.put(jsonObj);
System.out.println(topJson.get(0).toString());
How to remove the unnecessary brackets and create the intended Json data?

Instead of:
secon.put("secon", seconArray);
Try:
prim.put("secon", seconArray);
And remove:
Main.put(secon);

Related

Add new key,value and update existing value of key in JSON file in java

My json file contains data as below : filename: "masterData.json"
{
"Devices":[
{"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":"available"
},
{
"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":"available"
}
],
"Organization":[
{
"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h",
}
],
"DeviceModels":[
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
}
]
}
I need to add deviceNumber and value for each of my devices and also update the Status from available to active so that my "masterData.json" would look like
{
"Devices":[
{
"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":**"active"**,
**"deviceNumber":"123456D"**
},
{
"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":**active**,
**"deviceNumber":"1234f"**
}
],
"Organization":[
{
"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h",
}
],
"DeviceModels":[
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
}
]
}
Kindly help me with the java code.
i tried with below java code and couldn't achieve.
FileReader reader = new FileReader(utility.getValue("MasterJsonPath"));
JsonObject jsonObj = (JsonObject) parser.parse(reader);
JsonArray deviceListFromJSON = (JsonArray) jsonObj.get("Devices");
for (int i = 0; i < deviceListFromJSON.size(); i++) {
JsonObject devices = (JsonObject) deviceListFromJSON.get(i);
ObjectMapper mapper = new ObjectMapper();
devices.addProperty("device number", "device value");
deviceListFromJSON.add(devices);
mapper.writer().writeValue(new File(utility.getValue("MasterJsonPath")),deviceListFromJSON);
}
}
First of , your fisrt json code is malformed ( extra commas , missing {"Devices" , .. ).
I tried to correct it :
{"Devices": [
{"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":"available"
},
{"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":"available"
}],
"Organization": [
{"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h"
}],
"DeviceModels":[
{"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{"BrandName":"",
"ModelNameValue":"",
"Config":""
}]}
For the java Code , try to save the file at the end of the for loop.
And write the whole jsonobject "jsonObj" , not only the deviceListFromJSON.
Also , use addProperty on both "deviceNumber" and "Status".Hope it helps :)
FileReader reader = new FileReader("file.json");
JsonParser parser = new JsonParser() ;
JsonObject jsonObj = (JsonObject) parser.parse(reader);
JsonArray deviceListFromJSON = (JsonArray) jsonObj.get("Devices");
reader.close();
for (int i = 0; i < deviceListFromJSON.size(); i++) {
JsonObject devices = (JsonObject) deviceListFromJSON.get(i);
devices.addProperty("deviceNumber", "1234f");
devices.addProperty("Status", "active");
}
BufferedWriter writer = new BufferedWriter(new FileWriter("file.json"));
writer.write(jsonObj.toString());
writer.close();

How to extract JSONArray and JSONObject from a JSON in Java

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));

How would i get the values from the Coords Array from this JSON?

{
"type":
"coll",
"locations":[
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.6]
}
},
{"geometry":
{"Coords":
[54.64999833333333,46.6]
}
}
]
}
In java using json.simple,here the code:
Here i assume the json data is present in file.json
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray loc= (JSONArray) jsonObject.get("locations");
Iterator i = loc.iterator();
while (i.hasNext()) {
JSONObject geo = (JSONObject) (i.next());
JSONObject coords = (JSONObject)geo.get("geometry");
String coord= (String)coords.get("Coords");
System.out.println(coord);
}

Class cast exception [JSONArray cannot be cast to org.json.simple.JSONObject]

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.

issue in looping

I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}
Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);
JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.

Categories

Resources