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");
Related
I'm trying to create a geojson file dinamically extracting data from database.
And when geojson is created parse to inputStream to store it in a path with fileManager.
I would like load from database an have this scheme. Features contains an array of features and each feature contains an id, properties object with values and a geometry field that contains an array.
This is how to should be loaded from database: (Scheme 1)
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "AFG",
"properties": {
"name": "Afghanistan"
},
"geometry": {
"type": "Polygon",
"coordinates": [...]
}
}]
}
I have two problems:
When I make the request from postman show me my geojson scheme like this: (Scheme 2)
[{
"geometry": {
"coordinates": [...],
"type": "Polygon"
},
"type": "Feature",
"table_id": 1,
"properties": {
"name": "Afghanistan"
}
}]
And when download file store it on folderPath with fileManager look like this: (Scheme 3)
[{
geometry = {
coordinates = []
type = Polygon
},
type = Feature,
table_id = 1,
properties = {
name = Afghanistan
}
}]
So my problems are:
How can load from database each feature and show like scheme 1??
Why when store the file replace : by =???
If I work with huge files how can create the file and not use a lot of memory???
Thanks
Here is my code:
public List<Object> getGeoJsonFromTable(String nameTable) {
String SQL = "SELECT table_id, CAST(properties AS text) as properties, ST_AsGeoJSON(geom) as geometry FROM " + nameTable + " ORDER BY table_id ASC;";
List<Map<String, Object>> result = jdbcTemplate.queryForList(SQL);
JSONObject geojson = new JSONObject();
geojson.put("type", "FeatureCollection");
JSONArray json = new JSONArray();
for (int i=0; i<result.size(); i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", "Feature");
jsonObject.put("table_id", result.get(i).get("table_id") );
jsonObject.put("geometry", serializeProperty( result.get(i).get("geometry").toString() ) );
jsonObject.put("properties", serializeProperty( result.get(i).get("properties").toString() ) );
json.put(jsonObject);
}
geojson.put("feautures", json);
List<Object> gson = json.toList();
String fileName = nameTable + "_" + String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()) + ".geojson";
Path folderPath = Paths.get(ValidationUtil.initializeField(null, ""));
String fileNewPath = folderPath.resolve(fileName).toString();
try {
fileManager.getFileStore().saveFile(new ByteArrayInputStream( gson.toString().getBytes("UTF-8") ), fileNewPath);
} catch (UnsupportedEncodingException e) {
log.error("ERROR: " + e.getMessage().toString());
e.printStackTrace();
}
return gson;
}
SOLUTION:
I've resolved how to create a geojson file from database, but I would like to do it with a better implementation. How can do it with a better implementation??
public String getGeoJsonFromTable(String nameTable) {
String SQL = "SELECT table_id, CAST(properties AS text) as properties, ST_AsGeoJSON(geom) as geometry FROM " + nameTable + " ORDER BY table_id ASC;";
List<Map<String, Object>> result = jdbcTemplate.queryForList(SQL);
JSONObject geojson = new JSONObject();
geojson.put("type", "FeatureCollection");
JSONArray json = new JSONArray();
for (int i=0; i<result.size(); i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", "Feature");
jsonObject.put("id", result.get(i).get("table_id") );
jsonObject.put("geometry", serializeProperty( result.get(i).get("geometry").toString() ) );
jsonObject.put("properties", serializeProperty( result.get(i).get("properties").toString() ) );
json.put(jsonObject);
}
geojson.put("feautures", json);
String fileName = nameTable + "_" + String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()) + ".geojson";
Path folderPath = Paths.get(ValidationUtil.initializeField(null, ""));
String fileNewPath = folderPath.resolve(fileName).toString();
try {
fileManager.getFileStore().saveFile(new ByteArrayInputStream( geojson.toString().getBytes("UTF-8") ), fileNewPath);
} catch (UnsupportedEncodingException e) {
log.error("ERROR: " + e.getMessage().toString());
e.printStackTrace();
}
return geojson.toString();
}
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 :)
Okay so the output I would like to get is this:
{
"id": 460,
"position": {
"x": 3078,
"y": 3251,
"z": 0
},
"random-walk": true,
"walk-radius": 1
},
But the one I currently get is:
{
"id": 460,
"position": "{
"x": 3078,
"y": 3251,
"z": 0
}",
"random-walk": true,
"walk-radius": 0
},
The problem is the position object that I am trying to convert to json.
The code I tried:
Path path = Paths.get("./npcs.json");
File file = path.toFile();
file.getParentFile().setWritable(true);
if (!file.getParentFile().exists()) {
try {
file.getParentFile().mkdirs();
} catch (SecurityException e) {
System.out.println("Unable to create directory for donator data!");
}
}
try (FileWriter writer = new FileWriter(file)) {
Gson builder = new GsonBuilder().setPrettyPrinting().create();
JsonObject object = new JsonObject();
Position pos = new Position(mob.absX, mob.absY, mob.heightLevel);
object.addProperty("id", mob.npcId);
object.addProperty("position", builder.toJson(pos));
object.addProperty("random-walk", mob.randomWalk);
object.addProperty("walk-radius", mob.walkingType);
writer.write(builder.toJson(object));
writer.close();
} catch (Exception e) {
System.out.println("Something went wrong with saving for mob !");
e.printStackTrace();
}
Does anyone has a clue on how to get the first result? So without the double-quotes.
Use this
object.add("position", new Gson().toJsonTree(pos));
instead of
object.addProperty("position", builder.toJson(pos));
result should than look like this:
"position": {
"x": 10,
"y": 50
},
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("Name","Name no." + i);
address.put("Country", "Country no." + i);
addresses.put(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
out.println("Error during json formatting" + jse.getMessage());
}
I would recommend using a JSONObject for your main JSON. After that, add each of the components. For a vector, add a json array. Here is a simple example I used to understand this better.
You can use your own java objects to be precise. Gson accesses the fields in your class using reflection, so you won't have to parse anything manually.
For example in your case:
import com.google.gson.annotations.SerializedName;
public class Walk {
private int id;
private Position position;
#SerializedName("random-walk")
private boolean randomWalk;
#SerializedName("walk-radius")
private int walkRadius;
}
public class Position {
private int x,y,z;
}
Then use
Gson gson = new Gson();
Walk walk = gson.fromJson(yourJson, Walk.class);
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: