com.amazonaws.util.json.JSONObject Below is the List, i want to convert it into json string.
List<JSONObject> jsonObjlist
is
[{"Attribute":"EmailAddress","Value":"abc@yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}, {"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":"abc@yahoo.com"}},{"map":{"Attribute":"Source","Value":"Missing_Fixed"}},{"map":{"Attribute":"mx_Lead_Status","Value":"Registered User"}},{"map":{"Attribute":"mx_Age","Value":""}},{"map":{"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}},{"map":{"Attribute":"mx_Registration_Source","Value":"EMAIL"}}]
Desired out put is
"[{"Attribute":"EmailAddress","Value":"abc@yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]"
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.
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", "abc@yahoo.com")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "abc@yahoo.com1")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));
The output is
[{"Value":"abc@yahoo.com","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"abc@yahoo.com1"}]
I suspect there are some toString() method in any object that you have override?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.