Represent JSON as an array of objects in JAVA
I would like to create a JSON string as an array of objects like this:
[
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
The JAVA JSON objects put method look开发者_如何学编程s like this: jsonObject.put(String key, Collection value);
When I enter my key and collection, my json looks like this:
{
"JSONObject": [
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
}
How can I get my json string to look like the first string when I am constrained to the signature of the put method?
If you're using the net.sf.json library, make yourself a JSONArray and put JSONObjects in it instead.
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("alertid","1");
array.add(obj);
What you need is a JSONArray
that you can then fill with JSONObject
's
Try something like this:
JSONArray arr = new JSONArray();
for (JSONObject item : collection)
{
arr.put(item);
}
Or, if you already have a Collection of JSONObject
's, you can simply write:
JSONArray arr = new JSONArray(yourFancyCollection);
Then, arr.toString()
will look like you asked.
精彩评论