parse Json array error "jsonObject cannot be resolved" - java

I have the following Json and I want to parse the array (cars) ,
[
{
"name": "John",
"city": "Berlin",
"cars": [
"audi",
"bmw"
],
when i tried with the following code i got error
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader(
"C:\\General\\Json\\json.txt"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
}
here is the error "jsonObject cannot be resolved"
how should i overcome it?
JSONArray cars = (JSONArray) jsonObject.get("cars");

you did not declared jsonObject

JSONArray cars = (JSONArray) person.get("cars"); try this instead of JSONArray cars = (JSONArray) jsonObject.get("cars"); this PSR also correct

Related

How to read a nested, non-array JSON in java?

I've a JSON file with:
"items": [
{
(...)
"volumeInfo": {
(...)
"readingModes": {
"text": true,
"image": true
},
(...)
}
How do I access 'image' and 'text' in "readingModes"? I've tried both
JSONArray readingModes = volumeInfo.optJSONArray("readingModes");
which worked for data with squared bracket, but in this case returns nulls
and
JSONObject readingModes = gobj.getJSONObject("readingModes");
which returns error - JSONObject["readingModes"] not found, where gobj is accessed:
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
(...)
}
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
JSONObject volumeInfo = gobj.getJSONObject('volumeInfo');
JSONObject readingModes = volumeInfo.getJSONObject('readingModes');
(...)
}
According to your JSON you need to do this.
Since readingModes is in volumeInfo, you first need to get JSON object of volumeInfo in order to access readingModes.

How to extract specific fields of JSON Array in Java and store it in String

I have JSON data and want to extract data of only specific fields in Java and store it in String.
Example,
From issues, key:651, From project name:test, updated, created This details for all records of array issues.
Sample JSON Data:
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "651",
"fields": {
"project": {
"name": "test",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
},
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "321",
"fields": {
"project": {
"name": "test2",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
}
]
Java code that I have tried so far jar used - (gson-2.8.5)
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
JsonObject issues0data = (JsonObject) issues0.get("key");
String issue_key = issues0data.get("issue_key").getAsString();
System.out.println("Value of key is -> " + issue_key); // java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Updated Code
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues_data = (JsonArray) object.get("issues");
for(int i=0; i<issues_data.size(); i++)
{
JsonObject issues = (JsonObject) issues_data.get(i);
String issues_key = (String) issues.get("key").toString();
String project_name = (String) issues.get("name").toString(); // returns null
}
You can convert to string when you get the value.
Change your code like this see if it helps.
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
String issue_key = (String) issues0.get("key");//<---here
System.out.println("Value of key is -> " + issue_key);
Update
If you want all values just put it inside "for":
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
Update 2
The data "updated" and "created" are not inside "issues" they are inside "fields" to get access to them you need to get them from "fields". You have to go inside level by level to get access to variables:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
JsonObject fields = (JsonObject) issues.get("fields");
JsonObject project = (JsonObject) issues.get("project");
String project_name = (String) project.get("key");
String fields_updated = (String) fields.get("updated");
String fields_created = (String) fields.get("created");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
You are getting an error because you are casting a JsonPrimitive to JsonObject. So instead of using
JsonObject issues0data = (JsonObject) issues0.get("key");
you should do
String issues0data = issues0.get("key").getAsString();
System.out.println("Value of key is -> " + issues0data);
Here, calling getAsString() will invoke JsonPrimitive.getAsString() method. This will take care if the primitive is boolean/number/string and convert it to string.

JSONObject create Json object issue

I trying to create the code which generates the JSON data which should look like this
{
"Main": [
{
"prim": "Hello ",
"secon": [
{
"ads": "A Message"
}
]
}
]
}
The code I am trying with is generating like below
{
"Main": [
{
"prim": "Hello"
},
{
"secon": [
{
"ads": "A Message"
}
]
}
]
}
Code:
JSONObject prim = new JSONObject();
prim.put("prim", Hello");
JSONObject ads = new JSONObject();
ads.put("ads", "A Message");
JSONArray seconArray = new JSONArray();
seconArray.put(ads);
JSONObject secon = new JSONObject();
secon.put("secon", seconArray);
JSONArray Main = new JSONArray();
Main.put(prim);
Main.put(secon);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Main", Main);
JSONArray topJson = new JSONArray();
topJson.put(jsonObj);
System.out.println(topJson.get(0).toString());
How to remove the unnecessary brackets and create the intended Json data?
Instead of:
secon.put("secon", seconArray);
Try:
prim.put("secon", seconArray);
And remove:
Main.put(secon);

How would i get the values from the Coords Array from this JSON?

{
"type":
"coll",
"locations":[
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.6]
}
},
{"geometry":
{"Coords":
[54.64999833333333,46.6]
}
}
]
}
In java using json.simple,here the code:
Here i assume the json data is present in file.json
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray loc= (JSONArray) jsonObject.get("locations");
Iterator i = loc.iterator();
while (i.hasNext()) {
JSONObject geo = (JSONObject) (i.next());
JSONObject coords = (JSONObject)geo.get("geometry");
String coord= (String)coords.get("Coords");
System.out.println(coord);
}

To get json of requied form [duplicate]

how can I create a JSON Object like the following, in Java using JSONObject ?
{
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
],
"manager": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
}
I've found a lot of example, but not my exactly JSONArray string.
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Small reusable method can be written for creating person json object to avoid duplicate code
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
response.put("employees", employees );
response.put("manager", managers );
return response;
}
Please try this ... hope it helps
JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();
jsonObj1=new JSONObject();
jsonObj2=new JSONObject();
array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);
Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;

Categories

Resources