Get element from JSON file using getJSONArray() and getJSONObject() in Java - java

I would like to walk through the json file below and save the part after "coordinates".
The json file:
{"type": "FeatureCollection","features": [{"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": [[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
]
}
I've seen code using getJSONArray() and getJSONObject() here and here. This information helped me to select (in my case) the "geometry" tree.
My code so far (test2.geojson is the json file mentioned above):
String output = new String(Files.readAllBytes(Paths
.get("C:\\Users\\****\\Desktop\\test2.geojson")));
JSONObject obj = new JSONObject(output);
JSONArray jsonArray = obj.getJSONArray("features");
System.out.println(jsonArray);
However, this only rearranges the file and appends the first part to the end of the file.
[{"geometry":{"coordinates":[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]],"type":"LineString"},"type":"Feature","properties":{}}]
Any solutions to get the desired output of:
[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
]
}
Thanks in advance.
Cheers!

As "geometry" is a json object {}, "coordinates" is a json array [],
You should be doing
JSONArray jsonArray = obj.getJSONArray("features");
JSONArray resultArray = jsonArray.getJSONObject[0].getJSONObject("geometry").getJSONArray("coordinates")

Related

Parse Json from Java properties file using gson library

I need to read and parse a json array from java properties file. I'm able to read the properties file and get the json array String. But I'm unable to parse the json array and get the values. I'm using gson library. Here is the data from properties file
jsonarray = [ { key1 : value1, key2 : value2 } ]
Code:
Properties properties = new Properties();
properties.load(new FileInputStream(filePath));
String jsonArray = properties.getProperty("jsonarray")
JsonElement element = new JsonPrimitive(jsonArray);
JsonArray array = element.getAsJsonArray();
I'm getting IllegalStateException
java.lang.IllegalStateException: Not a JSON Array: "[ { key1 : value1, key2 : value2 } ]"
The problem is it is taking extra double quotes at the beginning and at the end.
I have tried adding quotes to keys and values, but with no success. I need to use gson library itself, so please don't suggest other libraries. I cannot create a POJO class for it and use new Gson().fromJson(jsonArray), so kindly please don't suggest that also.
I've searched and tried a lot without success. The method I referred is given here
Thanks in advance
Edit 1: I've tried the following in properties file
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]
and I got same exception like
java.lang.IllegalStateException: Not a JSON Array: "[ { \"key1\" : \"value1\", \"key2\" : \"value2\" } ]"
I tried to create a JsonArray object in code and print it
JsonArray array = new JsonArray();
JsonObject object = new JsonObject();
object.addProperty("key1", "value1");
object.addProperty("key2", "value2");
array.add(object);
System.out.println(array.toString());
The output was as below
[{"key1":"value1","key2":"value2"}]
The Javadoc of JsonPrimitive you've used here
JsonElement element = new JsonPrimitive(jsonArray);
states
Create a primitive containing a String value.
When you then do
JsonArray array = element.getAsJsonArray();
it'll obviously fail because element is a JSON String, not a JSON array. Just parse the JSON directly
JsonArray array = new Gson().fromJson(jsonArray, JsonArray.class)
This is all after you've changed your properties file content to be actual JSON
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]

JSON : how to save JSON Array using Java and loop till last JSON Object

I'm new to JSON and have below file. I have to save the array "steps" in java and need to loop the objects "duration" , "status" and "Keyword".
"steps": [
{
"result": {
"duration": 7128811788,
"status": "passed"
},
"line": 5,
"name": "The Browser is Launched and Smart Business URL is loaded",
"match": {
"location": "Common_Login.the_Browser_is_Launched_and_Smart_Business_URL_is_loaded()"
},
"keyword": "Given "
},]
I tried below but didn't worked.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./target/JSON/Output.json"));
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) jsonArray.get(i);
name = (String) jsonObjectRow.get("duration");
id = (String) jsonObjectRow.get("status");
uri = (String) jsonObjectRow.get("name");
status = (String) jsonObjectRow.get("location");
}
Refer here.
There are so many libraries build in for doing this task. But look at the question above.
If you want to use the built-in class from Java you can have a look here:
https://stackoverflow.com/a/17399110/3977134
You are missing the part from the parseJson function in the referenced answer.
For simplicity I'd suggest to you to use org.json which is just one of many good libraries to use for JSON parsing in Java. If you are interested see here:
Parse JSON with org.json
Parsing JSON in Java Using org.json

Getting a Value from a JsonArray using gson

I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}

Parsing nested json array in java

I have json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.
The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.
Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1

How to convert Json to JsobObject on android

I have a json structure like this:
[{
"name": "test",
"urlImg": "test",
"description": "test",
"urlLink": "test",
}]
And I want to retrieve the 4 values, I tried with:
JSONObject jsonObj = new JSONObject(jsonStr);
name = jsonObj.getString("TAG_TITLE");
I correctly download the json but name doesn't retrieve anything.. Am I parsing it wrong?
Your JSON is array [...] with one object {..}. So you need to
create JSONArray
get its only JSONObject
read its properties

Categories

Resources