gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:56:17 32 4
gpt4 key购买 nike

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

我得到的输出是

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

期望的输出是

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

最佳答案

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

JSONArray myArray = new JSONArray(jsonObjlist);

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

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

关于java - 如何在 java 中将列表 <JSONObject> 转换为 Json 字符串 (com.amazonaws.util.json.JSONObject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650379/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com