0

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 looks 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?

1
  • Can you post your example class? Thanks Commented Aug 4, 2011 at 17:19

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.