0

I need to generate the JSON string in following format:

[{"param1":"value1","param2":"value2"},{"param1":"value3","param2":"value4"}]

I tried to store data in following way:

JSONArray jsonArray = JSONArray();

HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("param1", "value1");
hmap.put("param2", "value2");
jsonArray.add(hmap);

hmap = new HashMap<String, String>();
hmap.put("param1", "value3");
hmap.put("param2", "value4");
jsonArray.add(hmap);

System.out.print(jsonArray.toString());

But it generated the json string in following format:

["{param1:value1,param2:value2}", "{param1:value3,param2:value4}"]

What changes are need to get the string in required format?

1

2 Answers 2

1

This should work. Use JSONObject instead of a map and add them to JSONArray.

JSONArray jsonArray = new JSONArray();

JSONObject jsonObject1= new JSONObject();
JSONObject jsonObject2= new JSONObject();

jsonObject1.put("param1", "value1");
jsonObject1.put("param2", "value2");
jsonArray.add(jsonObject1);


jsonObject2.put("param1", "value3");
jsonObject2.put("param2", "value4");
jsonArray.add(jsonObject2);

System.out.print(jsonArray.toString());

I would suggest a better alternative to use a third party library such as XStream, which does it for you.

Sign up to request clarification or add additional context in comments.

Comments

0

Use Jettison and it will do exactly what you want

import org.codehaus.jettison.json.JSONArray;

public class JSONPrintTest extends TestCase{

public void testPrinting(){
    JSONArray jsonArray = new JSONArray();

    HashMap<String, String> hmap = new HashMap<String, String>();
    hmap.put("param1", "value1");
    hmap.put("param2", "value2");
    jsonArray.put(hmap);

    hmap = new HashMap<String, String>();
    hmap.put("param1", "value3");
    hmap.put("param2", "value4");
    jsonArray.put(hmap);

    System.out.print(jsonArray.toString());
}

}

Output: [{"param1":"value1","param2":"value2"},{"param1":"value3","param2":"value4"}]

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.