Vinay Sawant
Vinay Sawant

Reputation: 378

How to convert List <JSONObject> to Json String in java (com.amazonaws.util.json.JSONObject)

com.amazonaws.util.json.JSONObject Below is the List, i want to convert it into json string.

List<JSONObject> jsonObjlist is

[{"Attribute":"EmailAddress","Value":"[email protected]"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"[email protected]"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]
ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String arrayToJson = objectMapper.writeValueAsString(jsonObjlist);

Output i get is

[{"map":{"Attribute":"EmailAddress","Value":"[email protected]"}},{"map":{"Attribute":"Source","Value":"Missing_Fixed"}},{"map":{"Attribute":"mx_Lead_Status","Value":"Registered User"}},{"map":{"Attribute":"mx_Age","Value":""}},{"map":{"Attribute":"mx_LoginID","Value":"[email protected]"}},{"map":{"Attribute":"mx_Registration_Source","Value":"EMAIL"}}]

Desired out put is

"[{"Attribute":"EmailAddress","Value":"[email protected]"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"[email protected]"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]"

Upvotes: 1

Views: 7747

Answers (2)

Deb
Deb

Reputation: 2972

You can also direct use

 String jsonString = new ObjectMapper().writeValueAsString(jsonObjectList) 

To get the desired ouptput

Here is the small example

List<JSONObject> jsons = new ArrayList<>();
jsons.add(new JSONObject(ImmutableMap.of("Attribute", "EmailAddress", "Value", "[email protected]")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "[email protected]")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));

The output is

[{"Value":"[email protected]","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"[email protected]"}]

I suspect there are some toString() method in any object that you have override?

Upvotes: -1

Florian Albrecht
Florian Albrecht

Reputation: 2326

You should convert your list to a JSON Array, and just use its toString() function:

JSONArray myArray = new JSONArray(jsonObjlist);

// ...
String arrayToJson = myArray.toString(2);

The int parameter specifies the indent factor to use for formatting.

Upvotes: 6

Related Questions