【发布时间】:2021-01-06 02:46:27
【问题描述】:
我有一个如下所示的 JSON,
{
"users": [
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007@gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
},
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007@gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
}
]
}
我有上面的代码,它能够像这样展平 JSON,
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "userName",
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"issuerAssignedId": "pdhongade007",
"extension_user_type": "user"
}
但代码仅返回 JSON 的“用户”数组中的最后一个用户。它不会返回第一个用户(基本上只返回最后一个用户,无论有多少用户),只是最后一个用户以扁平形式从“用户”数组中出来。
public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<String, Object>();
System.out.println("flatKeyValue : " + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
for (Iterator it = object.keys(); it.hasNext(); ) {
String key = (String) it.next();
Object next = object.get(key);
readValue(json, key, next);
}
}
static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i < array.length(); ++i) {
readValue(json, key, array.opt(i));
}
} else if (next instanceof JSONObject) {
readValues((JSONObject) next, json);
} else {
json.put(key, next);
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
}
请提出我哪里做错了或者我的代码需要修改。
【问题讨论】:
-
您的 JSON 不正确。使用它来检查它并使用有效的 JSON jsonformatter.curiousconcept.com/# 更新您的问题
-
那个 JSON 有什么不正确的地方吗?你能给我解释一下吗?因为它是一个包裹在数组“users”中的多维 JSON。
-
您检查过我在评论中添加的链接吗?它指出 JSON 缺少对象的右括号和数组的右括号。除此之外,您为什么要以这种方式存储用户?您可以创建一个名为 users 的数组并在其中存储多个用户对象。
-
对不起,我没有意识到我错过了 JSON,是的,你是对的,JSON 是错误的,我会更新答案。
-
我已经修复了 JSON,我的错误。
标签: java arrays json collections