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());
}
Related
I have some trouble with parsing a JSON response. The response data:
{
"deal": {
"categorie": {
"description": "Offres Shopping",
"idcategorie": "1",
"nom": "Shopping"
},
"conditions": "2 personne au plus",
"dateAjout": "2013-01-07T00:00:00+01:00",
"dateExp": "2013-01-31T00:00:00+01:00",
"description": "nuit dans un hotel 5 etoile",
"heurexp": "12",
"iddeal": "1",
"minutesexp": "30",
"prestataire": {
"adresse": "Qu zohour 44",
"codePostale": "12600",
"description": "Hotel 5 etoiles",
"idprestataire": "1",
"nom": "Hotel ronald",
"pays": "France",
"telephone": "99999999",
"ville": "Brest"
},
"prix": "80.0",
"prixHabituel": "200.0",
"tags": "hotel",
"titre": "Nuit 5 etoiles"
}
}
When trying to parse this response to a List<Deal> I get this exception:
com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
This is the code that I am using for the parse:
if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);
Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("deal"); // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}
System.out.println(deals.toString());
return "success";
}
thanks
Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:
"deal" : [{"attr" : "value"}, {"attr" : "value"}]
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 received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.
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.
I am having hard time to figure it out how to parse the following JSON (Dynamic):
[{
"existingData": [
0,
0
],
"guestId": {
"__type": "Pointer",
"objectId": "EB1rr6Lqtp"
},
"listingAddressGeopoint": {
"__type": "GeoPoint",
"latitude": 36.002702,
"longitude": -78.90682099999998
},
"numberOfListingImages": 1,
"preferredGender": "\"Female\"",
"urlOfListingBeds": [
"https://xyz.image0.jpg"
],
"urlOfPrimaryImage": null,
"createdAt": "2015-09-09T14:54:36.139Z",
"updatedAt": "2015-09-15T14:46:41.988Z",
"user": {
"createdAt": "2015-09-09T14:54:34.841Z",
"updatedAt": "2015-09-09T14:54:34.841Z"
}
}]
The problem is sometime data starts previuosData not from existingData. How can I get the array of urlOfListingBeds in list of Some object?
Model class
public class Image {
public List<String> urlOfListingBeds;
}
Edit-1
I tried to access it by following code but it is throwing an errror
for (int i = 0; i < rjson.size(); i++) {
rjson.getAsJsonObject(i);
}
where as rjson is JsonArray
Get the JsonArray from json object by calling getAsJsonArray(). Create a iterator by calling JsonArray#iterator, and iterate over each JsonElement, and get JsonObject by calling JsonElement#getAsJsonObject().
Once you have JsonObject, you will find the urlOfListingBeds.
Code:
JsonArray array= rjson.getAsJsonArray();
Iterator iterator = array.iterator();
List<String> urlOfListingBeds = new ArrayList<String>();
while(iterator.hasNext()){
JsonElement jsonElement = (JsonElement)iterator.next();
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray urlOfListingBed = jsonObject.getAsJsonArray("urlOfListingBeds");
if(urlOfListingBed!=null){
Iterator iter = urlOfListingBed.iterator();
while(iter.hasNext()){
JsonElement jsonElementChild = (JsonElement)iter.next();
if(jsonElementChild!=null)
urlOfListingBeds.add(jsonElement.getAsString());
}
}
}