com.amazonaws.util.json.JSONObject
下面是列表,我想将其转换为json字符串。

List<JSONObject> jsonObjlist

[{"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);


我得到的输出是

[{"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"}}]


期望的输出是

"[{"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"}]"

最佳答案

您应该将列表转换为JSON数组,并仅使用其toString()函数:

JSONArray myArray = new JSONArray(jsonObjlist);

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


int参数指定用于格式化的缩进因子。

09-10 20:19