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();
}
Related
I have this json that has " product code" inside this product code has another jsonobject and string.
What I want is that when I input the "product code" the suggested description will show.
I already get the display for suggested description when I input the product description code but it seems that it displaying in wrong way.
What I mean is that when I type the "product code" "BI" the display for suggested description is like this
{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}
here is my json
{
"BI": {
"desc": {
"MBIK": "MOUNTAIN BIKE",
"FBIK": "FOLDING BIKE",
"EBIK": "E-BIKE",
"OTHER": "OTHER"
},
"brand": {
"GNT": "GIANT",
"TRL": "TREEK",
"CNN": "CNDALE",
"STC": "SANTA",
"SCT": "SCOTT"
},
"category": "BICYCLE & EBIKE STORE"
},
"CA": {
"desc": {
"CARA": "CAR AUDIO",
"CARS": "CAR SPEAKER",
"TIRE": "CAR TIRE",
"OTHER": "OTHER"
},
"brand": {
"AIC": "AICHI",
"BRI": "BRIGDESTONE",
"CON": "CONTINENTAL",
"DUN": "DUNLOP",
"FAL": "FALKEN GR"
}
"category": "CAR ACCESORIES"
},
and so on.. {
}
}
here is the my code to parse my json to my fragment
private void loadLookupCategoryJson() {
mLookupProducts = new ArrayList<>();
mArrayStringLookupProduct = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadLookupBrandJSON());
Iterator<String> keys = json.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject obj = (JSONObject) json.get(key);
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
String category = obj.getString(Keys.CATEGORY);
LookupProducts lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
mArrayStringLookupProduct.add(String.valueOf(brand));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and here is my to get the brand dynamic field
} else if (format.equalsIgnoreCase(Keys.AUTO_COMPLETE_FIELD)) {
addTextViews(title);
addAutoCompleteField(desc, inputType, title, mKeys.get(i), mArrayStringLookupProduct, maxLength, minLength);
}
I expect the output should be like this
INPUT TEXT: T
SUGGESTED DISPLAY:GIANT
TREEK
SANTA
SCOTT
Display all values with "T"
actual output
INPUT TEXT: BI
SUGGESTED DISPLAY:{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}
In this line of code - mArrayStringLookupProduct.add(String.valueOf(brand));
You are adding whole jsonObject into mArrayStringLookupProduct ArrayList.
You only want JSONObject brand's values in this ArrayList.
You can make the following changes-
JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
JSONObject desc = obj.getJSONObject(Keys.CATEGORY_DESC);
String category = obj.getString(Keys.CATEGORY);
lookupProduct = new LookupProducts(key, brand, desc, category);
mLookupProducts.add(lookupProduct);
// iterate every brand key, fetch its value and add in arrayList
Iterator<String> brandKeys = brand.keys();
while(brandKeys.hasNext()) {
String bKey = brandKeys.next();
mArrayStringLookupProduct.add((String) brand.get(bKey));
}
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");
I am getting this error when I try to get the value for "Name" out of the following JSON:
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
My output looks like this:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
I understand that I could use optString and not get the error, but that will not give me the data stored in each node.
Here is a version that works with your unaltered JSON:
public static void main(String... args)
{
String json = "{\"data\":{\"viewer\":{\"allMountains\":{\"edges\":[{\"node\":{\"Name\":\"Sunday River\",\"Latitude\":44.4672,\"Longitude\":70.8472}},{\"node\":{\"Name\":\"Sugarloaf Mountain\",\"Latitude\":45.0314,\"Longitude\":70.3131}}]}}}}";
JSONObject obj = new JSONObject(json);
JSONObject data = obj.getJSONObject("data");
JSONObject viewer = data.getJSONObject("viewer");
JSONObject allMountains = viewer.getJSONObject("allMountains");
// 'edges' is an array
JSONArray edges = allMountains.getJSONArray("edges");
for (Object edge : edges) {
// each of the elements of the 'edge' array are objects
// with one property named 'node', so we need to extract that
JSONObject node = ((JSONObject) edge).getJSONObject("node");
// then we can access the 'node' object's 'Name' property
System.out.println(node.getString("Name"));
}
}
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();
Is it possible to create and parse json like this
{
"time1": { "UserId": "Action"},
"time2": { "UserId": "Action"},
"time3": { "UserId": "Action"}
}
with json-simple.jar
I would like to keep on updating the json with the element "time": { "UserId": "Action"}
Any help ? please
Yes it's possible just use this to create :
JSONObject obj=new JSONObject();
JSONObject timeObj = new JSONObject();
timeObj.put("UserId", "Action");
obj.put("time", timeObj);
and to parse
Object obj=JSONValue.parse(value);
JSONObject object=(JSONObject)obj;
JSONObject timeObj = obj.get("time");
String action = timeObj.get("UserId");
but I don't recommends you to create JSON with format like that, the JSONObject property key must be unique, I suggest you to use JSONArray instead of JSONObject
I hope this can help you
Your JSON is incorrect. You can't have duplicate time keys. Convert it into a JSON array instead.
{
"time": [
{ "UserId": "Action"},
{ "UserId": "Action"},
{ "UserId": "Action"}
]
}
Here's how you can parse this JSON string
String json =
"{\n" +
" \"time\": [\n" +
" { \"UserId\": \"Action\"},\n" +
" { \"UserId\": \"Action\"}\n" +
" ]\n" +
"}";
JSONObject jsonRoot = new JSONObject(json);
JSONArray timeArray = jsonRoot.getJSONArray("time");
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"}]
Here's how you can add a new object to this JSON array
timeArray.put(new JSONObject().put("Admin", "CreateUser"));
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"},{"Admin":"CreateUser"}]