I have written a program that reads a simple json file:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
for (Object o : a)
{
JSONObject obj = (JSONObject) o;
String city = (String) obj.get("CITY");
System.out.println("City : " + city);
String loc = (String) obj.get("LOCATION");
System.out.println("Location : " + loc);
long el = (Long) obj.get("E_LEVEL");
System.out.println("Emergency Level : " + el);
long depth = (Long) obj.get("DEPTH");
System.out.println("Depth : " + depth);
long i = (Long) obj.get("INTENSITY");
System.out.println("Intensity :"+i);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
with my json file being:
[{"CITY":"MUMBAI","LOCATION":"a" ,"E_LEVEL": 6,"DEPTH":10,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"b" ,"E_LEVEL": 8,"DEPTH":20,"INTENSITY":4},
{"CITY":"MUMBAI","LOCATION":"c" ,"E_LEVEL": 3,"DEPTH":13,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"d" ,"E_LEVEL": 6,"DEPTH":12,"INTENSITY":4},]
I am working on a project that deals with earthquake alerts and want to read their JSON files however I cannot import them in JSON Array. The file I want to import looks like this:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1488472809000,
"url": "https:\/\/earthquake.usgs.gov\/earthquakes\/feed\/v1.0\/summary\/significant_week.geojson",
"title": "USGS Significant Earthquakes, Past Week",
"status": 200,
"api": "1.5.4",
"count": 2
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 5.5,
"place": "42km WSW of Anchor Point, Alaska",
"time": 1488420690658,....
Please tell what changes should be made.
If you are trying to read from features only, first you need to read the whole file as an object. Then you can, read the array part in the following way:
Object object = parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
JSONObject jasonObject = (JSONObject) object;
JSONArray features = (JSONArray) jasonObject.get("features");
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.
Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.
You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)
I have a JSON object like this :
{
"Successful": true,
"Value": {
"Materials":[{
"MaterialID": 37628,
"MaterialID": 0,
"MaterialNo": 26868,
"Type": 0,
"MaterialName": Copper
}],
"Prices": []
}
}
I'm trying to get materials array like this :
public ArrayList<Material> parseMaterial (JSONObject object)
{
try
{
JSONArray materialArray = object.getJSONArray("Materials");
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMaterial", e.getMessage());
}
}
I get this exception :
JSONParser=>parseMaterial﹕ No value for Materials
Can you tell me what is wrong with the code? Thanks.
You're missing a step: change
JSONArray materialArray = object.getJSONArray("Materials");
to
JSONObject value = object.getJSONObject("Value");
JSONArray materialArray = value.getJSONArray("Materials");
getJSONArray does not 'search' the entire object (this could give unpredictable results if you have multiple Materials in the object), only the first level.
New to Android and Java in general and I'm learning how to make a JSON call. To do so, I'm following this guide: http://mobiforge.com/design-development/consuming-json-services-android-apps
Here's where things get confusing for me. The author of that tutorial wants the reader to call this API: http://ws.geonames.org/findNearByWeatherJSON?lat=37lng=122
Which returns a JSON object in this format:
{
"weatherObservation": {
"clouds":"scattered clouds",
"weatherCondition":"n/a",
"observation":"KCFV 090852Z AUTO 06005KT
10SM SCT090 SCT110 24/20 A3000 RMK AO2
SLP148 T02390200 53002",
"windDirection":60,
"ICAO":"KCFV",
"seaLevelPressure":1014.8,
"elevation":225,
"countryCode":"US",
"lng":-95.56666666666666,
"temperature":"23.9",
"dewPoint":"20",
"windSpeed":"05",
"humidity":78,
"stationName":"Coffeyville, Coffeyville
Municipal Airport",
"datetime":"2012-07-09 08:52:00",
"lat":37.083333333333336
}
}
Pretty straight forward, except that the API is no longer valid/has limits. In order to finish the project I've instead opted to call this API: http://api.openweathermap.org/data/2.5/weather?lat=37.77&lon=-122.419
Which returns the JSON in this format
{
"coord": {
"lon": 139,
"lat": 35
},
"sys": {
"country": "JP",
"sunrise": 1369769524,
"sunset": 1369821049
},
"weather": [
{
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"main": {
"temp": 289.5,
"humidity": 89,
"pressure": 1013,
"temp_min": 287.04,
"temp_max": 292.04
},
"wind": {
"speed": 7.31,
"deg": 187.002
},
"rain": {
"3h": 0
},
"clouds": {
"all": 92
},
"dt": 1369824698,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I can make the call just fine, but how do I display the "main" and "description" strings in the "weather" array? More specifically, how do I display this information as a Toast?
Here's what I have:
protected void onPostExecute(String result){
try {
JSONArray weatherArray = new JSONArray(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = wArray.getString(1);
String mainDescription = wArray.getString(2);
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
BecauseI am following the mobiforge Tutorial, I have not deviated anywhere else except for this particular block of code.
Thanks for the help!
Edit:
There are several solutions here that work see #swats and #user3515851. I have chosen #remees-m-syde due to it's simplicity. Primarily because his solution did not require that I go through the for loop.
I have used optJSONArray or optString, instead of getJSONArray or getString as "opt" will return "" if there is no value for that key.. it will not throw any exception like in case of getString()
Try below code
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.optJSONObject(i);
String mainWeather = weatherJsonObj.optString("main");
String mainDescription = weatherJsonObj.optString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
Parsing issue was there, You should have taken object from response result.
EDIT: No need of try catch block while using optJSONArray or optString.
You are unable to get the data because there is one json object inside the "weather" JSONArray.
JSONArray starts with - [
JSONObject starts with - {,
So first get the JSONArray and then the JSONObject inside it.
"weather": [ ----Array
{ ----Object
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
]
You have to get this JSONObject and then get the String from it like the below code showing.
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
JSONObject jobj = wArray.getJSONObject(0);
String mainWeather = jobj.getString("main");
String mainDescription = jobj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
When there is multiple object in Array, Get it as below.
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.getJSONObject(i);
String mainWeather = weatherJsonObj.getString("main");
String mainDescription = weatherJsonObj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(String result){
try {
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
for(int i=0;i<wArray.length,i++){
JSONObject object=wArray.getJSONObject(i);
String mainWeather=object.getString("main");
String mainDescription=object.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
I hope this one will help to you :)
I assume you obtained the weather array from parsing this JSON now to retrieve the values from it
JSONObject object=null;
try {
JSONObject object=array.getJSONObject(0);
String main=object.getString("main");
String description=object.getString("description");
} catch (JSONException e) {
e.printStackTrace();
}
and now use the strings in your toast
Assuming result contains the JSON, here is how to get main, and description form weather :
JSONObject resJSON = new JSONObject(result);
JSONArray weatherArray = resJSON.getJSONArray("weather");
for(int i = 0; i < weatherArray.length(); i++) {
JSONObject weatherJSON = weatherArray.getJSONObject(i);
System.out.println(weatherJSON.getString("main"));
System.out.println(weatherJSON.getString("description"));
}
Recently, I found out json2pojo useful tool for json parsing, works with anything Jackson,Gson,Java etc.
Hope this will help you.
Try this
JSONObject weatherObject = new JSONObject(result);
JSONArray wArray = weatherObject.getJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject wObject = wArray.getJSONObject(i);
if(wObject.has("description")) {
Log.d("TAG", wObject.getString("description"));
}
if(wObject.has("main")) {
Log.d("TAG", wObject.getString("main"));
}
}
Use this
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = ((JSONObject)wArray.getJSONObject(0)).getString("main");
String mainDescription = ((JSONObject)wArray.getJSONObject(0)).getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
I'm trying to parse a json file using json simple library but I'm having some trouble getting the code to parse the json file. I've done some searching but every example's json file is formatted differently from the one I'm using. I'm able to query the full json file, but I can't get a specific piece of information from my json file and add it to a list (the list turns up empty).
The json file in question (this is a snippet of the original file for simplicity's sake):
{
"status": "ok",
"count": "2",
"data":{
"1":{
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3":{
"country": "U.K.",
"name": "Dell",
"id": 3
}
}
}
The code I've tried using:
List<String> list = new ArrayList<String>();
String json = myJSONFile; // myJSONFile is a place holder for the location of the file.
JSONObject jsonObject = (JSONObject) JSONValue.parse(json);
JSONObject data = (JSONObject) jsonObject.get("data");
for (int x = 0; y > data.size(); y++)
{
JSONObject id = (JSONObject) data.get(y + "");
list.add((String) id.get("name");
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
As pointed out in the comments, you JSON isn't a valid one. You can try parsing it here.
The correct JSON appears to be:
{
"status": "ok",
"count": "2",
"data": {
"1": {
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3": {
"country": "U.K.",
"name": "Jeremy",
"id": 3
}
}
}
A couple of errors in your code:
1) You are trying to parse the JSON file location without reading it. You need to first read the file containing JSON string
List<String> list = new ArrayList<String>();
String json = "..\\json.txt";
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
2) Your loop doesn't make much sense. Here you want to try and iterate over the keys returned by your JSONObject represented by data
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
Here is the full working sample, modify per your need to make it more generic and best practices:
public static void main(String... args) {
try {
List<String> list = new ArrayList<String>();
String json = "..\\json.txt"; //Location of your json file
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: