如何在 java 中将列表 <JSONObject> 转换为 Json 字符串 (com.amazonaws.util.json.JSONObject)

Vin*_*ant 1 java json objectmapper

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

List<JSONObject> jsonObjlist

[{"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"}]
Run Code Online (Sandbox Code Playgroud)
ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String arrayToJson = objectMapper.writeValueAsString(jsonObjlist);
Run Code Online (Sandbox Code Playgroud)

我得到的输出是

[{"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"}}]
Run Code Online (Sandbox Code Playgroud)

期望的输出是

"[{"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"}]"
Run Code Online (Sandbox Code Playgroud)

Flo*_*cht 6

您应该将列表转换为 JSON 数组,然后使用它的toString()函数:

JSONArray myArray = new JSONArray(jsonObjlist);

// ...
String arrayToJson = myArray.toString(2);
Run Code Online (Sandbox Code Playgroud)

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