Error parsing the JSON file using Java - java

I am getting the error while parsing the the following JSON file. If anybody please help me out, highly appreciated!
{"Name":"Abc", "Author":"fgd", "Company List":{"Company":"C1","Companyone":"Compa2"}}
Here is my code:-
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/abcdefgh/Documents/File1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
// JSONArray companyList= new JSONArray();
//companyList.add(obj);
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
System.out.println("Company List:");
/* for (int i=0;i<2;i++){
System.out.println(companyList.get(i));
}
*/Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Output:-
Name: Abc
Author: fgd
java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to org.json.simple.JSONArray at
com.selenium.test.JSONRead.main(JSONRead.java:29)

The property type of "Company List" property is object, not an array.
Replace the line
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
for:
JSONObject companyList = jsonObject.getJSONObject("Company List");
If you want to get the values ​​of this object, you can do the following:
JSONObject companyList = jsonObject.getJSONObject("Company List");
String company = companyList.getString("Company");
And remember to get the value of a property of a JSONObject which is an array, you must use the method getJSONArray.

companyList is a JSON Object, not an array. That's why you are getting that class cast exception.

Related

How to combine two or more JSON objects into one JSONObject

I've two JSON Objects as below
firstJSON: {"200":"success"}
secondJSON: {"401":"not found"}
I need to combine them as {"codes":{"200":"success"},{"401":"not found"}} using java.
I tried in 3 ways but couldn't achieve the desired output. Could you please help with code snippet?
code which I've tried as below
JSONObject firstJSON = new JSONObject();
firstJSON.put("200", "success");
String firstJSONStr = firstJSON.toString();
System.out.println("firstJSONStr--> " + firstJSONStr);
JSONObject secondJSON = new JSONObject();
secondJSON.put("401", "not found");
String secondJSONStr = secondJSON.toString();
System.out.println("secondJSONStr--> "+secondJSONStr);
String finalJSONStr = firstJSONStr + "," + secondJSONStr;
JSONObject finalJSON1 = new JSONObject();
finalJSON1.put("codes", new JSONObject(finalJSONStr));
System.out.println("finalJSON1--> " + finalJSON1.toString());
JSONObject finalJSON2 = new JSONObject();
finalJSON2.put("codes", finalJSONStr);
System.out.println("finalJSON2--> " + finalJSON2.toString());
JSONObject finalJSON3 = new JSONObject();
ArrayList<JSONObject> jsonArray = new ArrayList<JSONObject>();
jsonArray.add(firstJSON);
jsonArray.add(secondJSON);
finalJSON3.put("codes", jsonArray);
System.out.println("finalJSON3--> " + finalJSON3.toString());
Output:
firstJSONStr--> {"200":"success"}
secondJSONStr--> {"401":"not found"}
finalJSON1--> {"codes":{"200":"success"}}
finalJSON2--> {"codes":"{\"200\":\"success\"},{\"401\":\"not found\"}"}
finalJSON3--> {"codes":[{"200":"success"},{"401":"not found"}]}
Your expected JSON {"codes":{"200":"success"},{"401":"not found"}} is invalid. You can verify it with https://jsonlint.com/ which will produce an error:
Error: Parse error on line 4:
...00": "success" }, { "401": "not foun
---------------------^
Expecting 'STRING', got '{'
You most likely want an array to group the first and second object which results in below JSON (do notice the square brackets [ and ]):
{"codes":[{"200":"success"},{"401":"not found"}]}
This can be achieved with:
JSONObject first = new JSONObject();
first.put("200", "success");
JSONObject second = new JSONObject();
second.put("401", "not found");
JSONArray codes = new JSONArray();
codes.put(first);
codes.put(second);
JSONObject root = new JSONObject();
root.put("codes", codes);
System.out.println(root);
Got the logic finally.
JSONObject successJSON = new JSONObject();
successJSON.put("description", "success");
JSONObject scJSON = new JSONObject();
scJSON.put("200", successJSON);
JSONObject failJSON = new JSONObject();
failJSON.put("description","failure");
scJSON.put("401", failJSON);
JSONObject finalJSON = new JSONObject();
finalJSON.put("codes", scJSON);
System.out.println("finalJSON --> "+finalJSON.toString());

Get dynamically list of object using json.simple

Asking after searching and trying many examples .
I'm trying to dynamically get list of values from json in order to insert into array .
The json looks like :
{
"Test_name":"mft",
"parameters":[
{
"Remotehost":"vl-tlv-ctm-qa22",
"Ftptype":"sftp",
"file_name":"blabla.txt"
}
]
}
i'm using the following code :
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:/temp/test.txt"));
JSONObject jsonObject = (JSONObject) obj;
String testname = (String) jsonObject.get("Test_name");
System.out.println(testname)
JSONArray msg = (JSONArray) jsonObject.get("parameters");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
System.out.println(factObj);
the output is :
mft
{"Remotehost":"vl-tlv-ctm-qa22","file_name":"blabla.txt","Ftptype":"sftp"}
how do i break the pairs in the nested so i can use the as variables and not as single line ?
Thanks ,
Zohar
You can get the pairs as key-value pair from JSONObject as below:
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
for (Object key : factObj.keySet()) {
System.out.println(key+":"+factObj.get(key));
}
}

Create JSON in 2D array to store key value pair

I have a question that would like to seek your expertise on.
I have Class call Technology and i retrieve data from the DB as object list of Technology classtechnologyList= getProjectBD().getAllTechnology();
my question is how to store data as key value pair in Json array.
This is my code
JSONArray technologyArray=new JSONArray();
for (Technology technology : technologyList) {
JSONArray gridRow=new JSONArray();
gridRow.put(technology.getTechnologyId());
gridRow.put(technology.getTechnologyName());
technologyArray.put(gridRow);
}
I need to pass this data to select option in my jsp as id and name.
ex:-[1:JAVA,2:C#...]
Try to use com.google.gson.* elements like that :
private JsonArray serializetechnologies(List<Technology> technologyList) {
JsonArray jsonArray = new JsonArray();
for (Technology technology : technologyList) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(technology.getTechnologyId()+"", technology.getTechnologyName());
jsonArray.add(jsonObject);
}
return jsonArray;
}
And if you want to get value :
for (JsonElement jsonElement : jsonArray) {
JsonObject jsonObject = (JsonObject) jsonElement;
String name = jsonObject.get(technologyX.getTechnologyId() + "").getAsString();
System.out.println("The name of technology witch Id = " + technologyX.getTechnologyId() + " is : "
+ name);
}
I hope that will help :)

How to retrieve JSON data inside an JSON object?

I have a JSON Object that looks like this :
"TripList":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestTrip.xsd",
"servertime":"11:27",
"serverdate":"2013-04-02",
"Trip":[{
"Leg":{
"name":"Spårvagn 3",
"type":"TRAM",
"id":"9015014500300079",
"direction":"Kålltorp",
"fgColor":"#004b85",
"bgColor":"#ffffff",
"stroke":"Solid",
"accessibility":"wheelChair",
"Origin":{
"name":"Brunnsparken, Göteborg",
"type":"ST",
"id":"9022014001760004",
"routeIdx":"19",
"time":"11:27",
"date":"2013-04-02",
"track":"D ",
"rtTime":"11:31",
"rtDate":"2013-04-02",
"$":"\n"
}
to get the name inside the Leg object is working fine.
But if I wanna get thetime inside the Origin object how do I do that?
My code is like this so far:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
Long time = (Long) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
}
And in the console it say like this :
{"routeIdx":"19","id":"9022014001760004","rtDate":"20130402","time":"15:02","$":"\n","name:"Brunnsparken, Göteborg","track":"D ","rtTime":"15:06","date":"2013-04-02","type":"ST"}
Spårvagn 3
null
null
So basiclly i am getting the name Spårvang 3 already. But I wanna get the time.
so the time that I am trying to get out by using jsonObj.get("time"); is giving a null value.
Whats the problem and how can I get the time from the object "Origin"??
Since "Time" is part of the "Origin"-object, you would need to extract the "Origin"-object first:
JSONOject origin = (JSONObject) jsonObj.get("Origin");
And then:
String time = origin.getString("time");
You are getting 'time' and 'track' properties of 'Leg' object, not the 'Origin' object..
It should be:
JSONParser parser = new JSONParser();
Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("TripList");
JSONArray array = (JSONArray) locationList.get("Trip");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
jsonObj = (JSONObject) jsonObj.get("Leg");
String line = (String) jsonObj.get("name");
Planner.getPlanner().setLines(line);
System.out.println(jsonObj.get("Origin"));
// Added this line
jsonObj = (JSONObject) jsonObj.get("Origin");
String time = (String) jsonObj.get("time");
String track =(String) jsonObj.get("track");
System.out.println(line);
System.out.println(time);
System.out.println(track);
}
Do following code
JSONOject origin = (JSONObject) jsonObj.get("Origin");
String time = (String) origin.getString("time");
them use SimpleDateFormat to parse time string and get date object

Parsing String to JsonObject using GSON gives IllegalStateException: This is not a JSON Object

I have the following code:
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
It's because due to the JSON structure..
I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
This should give you some basic idea.
ArrayList<String> roomTypes = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for(int i =0; i<jsonArray.length(); i++){
roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}
The problem with the code is that roomList is not a JsonObject as evident in the printed output. It's actually a JsonArray.
To fix the code, call .getAsJsonArray() (instead of .getAsJsonObject())
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);

Categories

Resources