How to convert Json to JsobObject on android - java

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

Related

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

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

Searching JSon string using java

I am new To JSon and i want to search the following json string and get the required output.
String:
{"status":"Success","code":"200","message":"Retrieved Successfully","reason":null,"
"projects":
[
{
"projectName": "example",
"users":
[
{
"userName": "xyz",
"executions":
[
{
"status": "check",
"runs":
[
{
"Id": "------",
"Key": "---"
}
],
"RCount": 1
}
],
"RCount": 1
}
],
"RCount": 1
},
Like that i have many projects and now , if i give projectname and username as input i wantt to get its status as output.
Is it possible?If yes how?
You may use JSONObject for this.
JSONObject json = new JSONObject(string);
JSONArray[] projectsArray = json.getJSONArray("projects");
for(int i = 0; i < projectsArray.length; ++i)
{
String projectName = projectsArray[i].getString("projectName");
...
}
Use the same method to get the users.
You can use gson library. Using gson convert your json string to Map and then you can iterate through map to get required item
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(jsonString, type);
You can use the Google gson to map your json data structure to a Java POJOs.
Example :
You can have Projects class containing list/array of Users.
Users class containing list/array of Executions and so on.
Gson library can easily map the json to these classes as objects and you can access your data in a more elegant manner.
Here are a few references :
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Get element from JSON file using getJSONArray() and getJSONObject() in 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")

how to create jsonObject according this structure?

Here is the structure of wanted JSON string
"1" : {
"Class': "group"
"text": "test1"
}
"2" : {
"Class': "group"
"text": "test1"
}
How can I create an jsonObject in Java that has this JSON representation?
You can either directly create the structure with Strings, or use a library that will create JSON objects in a more object oriented manner.
See https://stackoverflow.com/questions/338586/a-better-java-json-library for some discussion on various JSON libraries and their pros/cons.
You can also always go with JSON's official library: http://json.org/java/
Use JSONObject Class from net.sf.json.JSONObject like this:
JSONObject jsonObject=new JSONObject();
JSONObject childObject=new JSONObject();
childObject.put("class", "group");
childObject.put("text", "test1");
jsonObject.put("1", childObject);
jsonObject.put("2", childObject);
System.out.println(jsonObject.toString());

Categories

Resources