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();
Answer from Grammin on Stack Overflowjson - How to create correct JSONArray in Java using JSONObject - Stack Overflow
java - Getting JSONObject from JSONArray - Stack Overflow
java - How can I turn a JSONArray into a JSONObject? - Stack Overflow
java - How to convert JSONObjects to JSONArray? - Stack Overflow
Videos
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 :)
JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);
Which in JSON will be {"arrayName":[...]}.
I have JSONObject like this: {"status":[{"Response":"success"}]}.
If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.
JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);
Converting the JSONArray to JSON Object:
Iterator<String> it=obj.keys();
while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));
}
}
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
Even shorter and with json-functions:
JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example: [{"name":"item 1"},{"name": "item2"} ]
On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item.
For example: {"name": "item1", "description": "a JSON object"}
Of course, JSON arrays and objects may be nested inside one another. One common example of this is an API that returns a JSON object containing some metadata alongside an array of the items matching your query:
{"startIndex": 0, "data": [{"name": "item 1"},{"name": "item2"} ]}
The difference is the same as a (Hash)Map vs List.
JSONObject:
- Contains named values (key->value pairs, tuples or whatever you want to call them)
- like
{ID : 1}
- like
- Order of elements is not important
- a JSONObject of
{id: 1, name: 'B'}is equal to{name: 'B', id: 1}.
- a JSONObject of
JSONArray:
- Contains only series values
- like
[1, 'value']
- like
- Order of values is important
- array of
[1,'value']is not the same as['value',1]
- array of
Example
JSON Object --> { "":""}
JSON Array --> [ , , , ]
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
Hi,
I am reading json into a Java program, where I am attempting to process it. I'm having some challenges figuring out how to dig down into the data structure, in order to iterate through some of the deeper lists. I'm attaching below excerpts of the Java, and the toy/test json.
Here is the toy/test json:
{
"objects": [
{
"type": "object-1",
"coordinates": [
[
0,
5
],
[
5,
10
],
[
10,
15
],
[
15,
0
]
]
}
]
}What I WANT to do is grab the list of objects associated with the key "objects", and then iterate through the dictionaries that compose the list, further extracting components (coordinates, say, if the type is what i'm after).
The thing is, I don't know how to do this. The code below is an attempt, but it doesn't work.
Here's the Java excerpt:
JSONObject json;
void setup() {
size(800, 494);
// input json file
String inputJsonFile = "input.json";
String inputJsonFileContentsString = "";
try {
inputJsonFileContentsString = readFileIntoString( inputJsonFile );
}
catch (IOException e) {
e.printStackTrace();
}
//JSON parser object to parse read file
JSONObject inputJsonData = parseJSONObject( inputJsonFileContentsString );
// recover list of objects
JSONArray objects = inputJsonData.getJSONArray( "objects" );
// print json data: iterate over list of objects, retrieving type and coordinates
int arrayLength = objects.size();
for ( int i = 0; i < arrayLength; i++ ) {
// THIS DOESN'T WORK
// I want the next dictionary/hash, but how to retrieve it?
JSONObject objectDataHash = objects[ i ];
}
}Thank you. I normally work with Python, it's been a while since I've done a lot of coding in Java so I'm probably missing something obvious.