JSONObject firstObject = (JSONObject) jsonParser.parse(new FileReader(firstNamesPath));
I have this JSONObject, and I want to be able to access elements in the array inside of it. The object opens successfully, I just don't know how to access the array called "firstNames". It is in a file, and the object looks like this.
{
"firstNames": [
"Aaron",
"Abigail",
"Albert",
"Bob"
]
}
Edit: I am using org.json.simple.JSONObject . If this is not recommended, I am more than willing to change it.
There are several ways to retrieve the json array value:
Assume we have a jsonString
jsonString = "{\n" + " \"firstNames\": [ \n" + " \"Aaron\",\n" + " \"Abigail\",\n" + " \"Albert\",\n" + " \"Bob\"\n" + " ]\n" + "}";
(since many classes share similar names, I am using the groupId and artifactId for distinction.)
Simple cases: use generic JSONObjects and JSONArrays.
json-simple (which OP is using) json-simple website, maven :
org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser();
org.json.simple.JSONObject firstObject = (org.json.simple.JSONObject) jsonParser.parse(jsonString);
org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) firstObject.get("firstNames");
System.out.println(jsonArray);
JSON in Java (mentioned in adendrata's answer): JSON-Java doc, maven
org.json.JSONObject secondObject = new org.json.JSONObject(jsonString);
org.json.JSONArray jsonArray2 = secondObject.getJSONArray("firstNames");
System.out.println(jsonArray2);
gson: Gson, maven
com.google.gson.JsonObject thirdObject = com.google.gson.JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(thirdObject.get("firstNames").getAsJsonArray());
For more complicated use cases, if you'd like to define your own class, and want to deserialize JSON string to your class, then you can use Gson or Jackson:
// Create your own class:
/*
public class YourOwnClass {
private List<String> firstNames;
public List<String> getFirstNames() {
return firstNames;
}
}
*/
Gson gson = new Gson();
YourOwnClass customObject1 = gson.fromJson(jsonString, YourOwnClass.class);
System.out.println(customObject1.getFirstNames());
ObjectMapper mapper = new ObjectMapper();
YourOwnClass customObject2 = mapper.readValue(jsonString, YourOwnClass.class);
System.out.println(customObject2.getFirstNames());
you can use JSONArray to get array type of Json and looping to access each index
example:
JSONArray array = firstObject.getJSONArray("firstNames");
for (int i = 0; i < array.length(); i++) {
System.out.println("Hello i'm " + array.get(i));
}
Try to use this : com.alibaba.fastjson.JSONObject, and here's the dependency:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
Then you can directly use the getJSONArray method the answer shown above.
Related
i get a json object via an api:
Gson gson = new Gson();
JsonObject users = gson.fromJson(reader, JsonObject.class)
this is my json object:
{"users":"[{\"user_id\": \"100011\", \"name\": \"Tim Clark\"}, {\"user_id\": \"100083\", \"name\": \"Timmy Kent\"}]"}
and i try to loop through all users
JsonArray usersArray = users.getAsJsonArray();
for (JsonElement ua : usersArray) {
JsonObject ua = ua.getAsJsonObject();
String name = ua.get("name").getAsString();
System.out.println(name);
}
also tried this
JsonArray usersArray = users.get("users").getAsJsonArray();
for (JsonElement ua : usersArray) {
JsonObject ua = ua.getAsJsonObject();
String name = ua.get("name").getAsString();
System.out.println(name);
}
But I get always exceptions like this
java.lang.IllegalStateException: Not a JSON Array: "[{\"user_id\": \"100011\", \" ....
In my opinion it is a valid json array, what to I miss?
Your JsonArray is between quotes: it's evaluated as a String
{"users":[{\"user_id\": \"100011\", \"name\": \"Tim Clark\"}, {\"user_id\":
\"100083\", \"name\": \"Timmy Kent\"}]}
should work (quotes inside the array don't need to be escapted as well, like "users")
I have a problem with convert string to json.
Namely, my json string is:
{"serverId":2,"deviceId":736,"analysisDate":"2017-05-11T07:20:27.713Z","eventType":"Logs","eventAttributes":[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]}
My code:
try {
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray("eventAttributes");
System.out.println("ARRAY: " + array);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = new JSONObject(array.getJSONObject(i));
System.out.println("OBJ: " + obj);
}
} catch (JSONException ex) {
Exceptions.printStackTrace(ex);
}
System.out.println array is:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
but if I print obj is "{}", four times. So it is correct, because array has 4 elements, but why it is empty object? I'm using org.json.
Thanks
array.getJSONObject(i) is already returning you an object of type JSONObject you dont need to pass it to constructor of JSONObject class.
simply write
...
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println("OBJ: " + obj);
}
...
You're calling the JSONObject(Object) constructor, passing in a JSONObject (the element in the array). That constructor is documented as:
Construct a JSONObject from an Object using bean getters. It reflects on
all of the public methods of the object. For each of the methods with no
parameters and a name starting with "get" or
"is" followed by an uppercase letter, the method is invoked,
and a key and the value returned from the getter method are put into the
new JSONObject. [...]
Now JSONObject itself doesn't have anything that fits a bean getter, so you end up with no keys. You don't want to treat the JSONObject as a bean.
That's why your current code doesn't work. To fix it, just don't call the constructor - instead, use the fact that the array element is already a JSONObject:
JSONObject obj = array.getJSONObject(i);
Output with that change:
OBJ: {"name":"level","value":"INFO"}
OBJ: {"name":"type","value":"Video Blocked On"}
OBJ: {"name":"cameraId","value":"722"}
OBJ: {"name":"userId","value":"1"}
If you consider following example you can do it in 3 ways :
jsonString = {
"name" : "John",
"sport" : "Soccer",
"age" : 25,
"id" : 100,
"score" : [ 2, 1, 4, 5, 0, 1, 2, 3, 1]
}
String to JSON Object using GSON
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert Java object to JSON by using method toJson()
String str = g.toJson(p);
JSON String to Java object using JSON-Simple
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
String to JSON - Jackson Example
Player john = new ObjectMapper().readValue(jsonString, Player.class);
I tried to convert following JSON string into Array and got following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory at
net.sf.json.AbstractJSON.(AbstractJSON.java:54) at
net.sf.json.util.CycleDetectionStrategy.(CycleDetect‌​ionStrategy.java:36)
at net.sf.json.JsonConfig.(JsonConfig.java:65) at
net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)
JSON:
[
{
"file_name":"1.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.1",
"status":"Checked ",
"rev":"1",
"locking":"0"
},
{
"file_name":"2.xml",
"file_ext":"json/octet-stream",
"sr_no":"0.2",
"status":"Not Checked ",
"rev":"2",
"locking":"1"
},
{
"file_name":"3.xml",
"file_ext":"application/json-stream",
"sr_no":"0.3",
"status":"Checked ",
"rev":"1",
"locking":"3"
},
{
"file_name":"4.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.4",
"status":"Checked ",
"rev":"0.4",
"locking":"4"
}
]
Code:
JSONArray nameArray = (JSONArray) JSONSerializer.toJSON(output);
System.out.println(nameArray.size());
for(Object js : nameArray)
{
JSONObject json = (JSONObject) js;
System.out.println("File_Name :" +json.get("file_name"));
}
I know the question is about converting JSON String to Java Array, but I would like to also answer about how to convert the JSON String to an ArrayList using the Gson Library.
Since I spend a good amount of time in solving this, I hope my solution may help others.
My JSON string looks similar to this one -
I had an object named StockHistory, and I wanted to convert this JSON into an ArrayList of StockHistory.
This is how my StockHistory class looked -
class StockHistory {
Date date;
Double open;
Double high;
Double low;
Double close;
Double adjClose;
Double volume;
}
The code that I used to convert the JSON Array to the ArrayList of StockHistory is as follows -
Gson gson = new Gson();
Type listType = new TypeToken< ArrayList<StockHistory> >(){}.getType();
List<StockHistory> history = gson.fromJson(reader, listType);
Now if you are reading your JSON from a file, the reader's initialization would be -
Reader reader = new FileReader(fileName);
and if you are just converting a string to JSON object then, the reader's initialization would simply be -
String reader = "{ // json String }";
Hope that helps. Cheers!!!
You can create a java class with entities are: file_name, file_ext, sr_no, status, rev, locking in string type.
public class TestJson {
private String file_name, file_ext, sr_no, status, rev, locking;
//get & set
}
}
Then you call:
public static void main(String[] args) {
String json = your json string;
TestJson[] respone = new Gson().fromJson(json, TestJson[].class);
for (TestJson s : respone) {
System.out.println("File name: " + s.getFile_name());
}
}
So, you have a list of object you want.
Firstly I have to say your question is quite "ugly" and next time please improve your question's quality.
Answer:
Try to use com.fasterxml.jackson.databind.ObjectMapper
If you have a java class to describe your items in the list:
final ObjectMapper mapper = new ObjectMapper();
YourClass[] yourClasses = mapper.readValue(YourString, YourClass[].class);
Then convert the array to a List.
If you don't have a java class, just you LinkedHashMap instead.
ResponseEntity<BaseDto> entity = restTemplate.getForEntity("/get/code/IN", BaseDto.class);
System.out.println("entity : " + entity);
System.out.println("entity.getBody() : " + entity.getBody());
System.out.println(entity.getBody().getResponseObject());
As per above rest am getting below format:
{
systemTrack=
{
createUser=admin,
createDate=2016-03-01 18:11:17,
lastUpdatedUser=admin,
lastUpdatedDate=2016-03-01 18:11:17
},
countryCode=IN, countryName=INDIA
}
How to get the values from this format?
Maybe I was unclear with my question, but i got a solution through debug mode.
It was a format which is in Linked hash map ,so what I did was I just wrote below code for json conversion of LinkedHashMap.
LinkedHashMap m = (LinkedHashMap) object;
JSONObject jsonObject = new JSONObject(m);(package of org.json.JSONObject)
and then i assigned to custom class object using
Gson gson = new Gson();
String jsonString = jsonObject.toString();
Object obj = gson.fromJson(jsonString, type);
I am struggling to generate JSON String in Java.
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
JSONArray ja = new JSONArray();
JSONObject js = new JSONObject();
JSONObject j = new JSONObject();
String s = "[{\"shakil\",\"29\",\"7676\"}]";
js.put("id", "1");
js.put("data", s);
ja.add(js);
j.put("rows", ja);
System.out.println(j.toString());
actual output:
{"rows":[{"id":"2","data":"[{\"shakil\",\"29\",\"7676\"}]"}]}
expected output:
{"rows":[{"id":"2","data":["shakil", "29","7676"]}]};
Your s is a String which is not unquoted when put into a JSONObject. You must build another JSONArray for the value of data:
// using http://jettison.codehaus.org/
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerArray.put("shakil");
innerArray.put("29");
innerArray.put("7676");
innerObject.put("id", "2");
innerObject.put("data", innerArray);
outerArray.put(innerObject);
outerObject.put("rows", outerArray);
System.out.println(outerObject.toString());
Result:
{
"rows": [
{
"id": "2",
"data": [
"shakil",
"29",
"7676"
]
}
]
}
Write
String[] s = new String[] {"shakil", "29" , "7676"};
instead of
String s = "[{\"shakil\",\"29\",\"7676\"}]";
Check out gson, it'll provide you with a whole lot of options for serializing/deserializing your Java objects to/from JSON.
Example taken from the page
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
//(Serialization)
gson.toJson(ints); ==> prints [1,2,3,4,5]
gson.toJson(strings); ==> prints ["abc", "def", "ghi"]
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
Finally found answer for net.sf.json
JSONArray data1 = new JSONArray();
data1.add("shakil");
data1.add("29");
data1.add("100");
JSONObject inner1 = new JSONObject();
inner1.put("id", "1");
inner1.put("data", data1);
JSONArray list2 = new JSONArray();
list2.add(inner1);
JSONObject finalObj = new JSONObject();
finalObj.put("rows", list2);
System.out.println(finalObj);
Not being able to declare a JSON string in Java is huge pain. Mainly due to (a) no multiline strings (b) escaping double quotes makes it a mess wrt readability.
I work around this by using single quotes to declare the JSON string (using the standard multiline concatenation). Nothing fancy:
String jsonStr =
"{" +
"'address': " +
"{" +
"'name': '" + name + "'," +
"'city': '" + city + "'," +
"'street1': '"+ street1 +"'," +
"'street2': '"+ street2 +"'," +
"'zip': '" + zip + "', " +
"'state':'" + state + "'," +
"'country': '" + country + "'," +
"'phone': '" + phone + "'" +
"}" +
"}";
jsonStr = MyUtil.requote(jsonStr);
System.out.println(jsonStr);
MyUtil
public static String requote(String jsonString) {
return jsonString.replace('\'', '"');
}
Some might find this more cumbersome than declaring a Map but this works for me when I have to build a JSON with just string syntax.
I see a lot of problems when writing a json as String directly without using a Objectmapper or similar.
I would suggest you to write your Json (as you defined it):
{"rows":[{"id":"2","data":["shakil", "29","7676"]}]}
and then simply use this little online tool: http://www.jsonschema2pojo.org/
Which can convert a simply Json a Java-Class also with multiple classes. You can there choose during generation if you want to use Gson or Jackson later.
Gson is a little bit lightweighter and may is better for beginning. I prefer Jackson because you can create something like a computed property - but that's already to much detail.
https://code.google.com/p/google-gson/
After adding Gson all you need to do is:
Gson gson = new Gson();
MyGeneratedClass target = new MyGeneratedClass();
String json = gson.toJson(target);
As voila: you have generated a simple json without thinking about how to change it later!