gpt4 book ai didi

java - 使用重复键解析 json

转载 作者:行者123 更新时间:2023-11-29 08:28:16 30 4
gpt4 key购买 nike

我正在尝试解析在 java 中包含重复键的 Json 文件。我正在使用此答案中建议的方法 Parsing a json which contains duplicate keys .如果我对 Json 进行硬编码,则该方法可以正常工作,但如果我从文件中读取它,则只读取最后一个重复键。请帮忙,因为我想从文件中读取 Json。提前致谢。代码:

public class am {
public static void main(String args[]) throws Exception
{
JSONParser parser = new JSONParser();


Object obj = parser.parse(new FileReader("sample.json"));

JSONObject a=JSONObject.fromObject(obj);
JSONObject jsonObject=JSONObject.fromObject("{\n" +
" \"Data\": {\n" +
" \"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"c\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"f\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"h\"\n" +
" }\n" +
" },\"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"x\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"y\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"z\"\n" +
" }\n" +
" },\n" +
"
"\n" +
" }\n" +
"}");
System.out.println("Json objects are:::"+a);
System.out.println("Json objects are:::"+jsonObject);

}
}

Json 文件:

{
"Data": {
"A": {
"B": {
"C": "c",
"D": {}
},
"E": {
"F": "f"
},
"G": {
"H": "h"
}
},"A": {
"B": {
"C": "x",
"D": {}
},
"E": {
"F": "y"
},
"G": {
"H": "z"
}
},

}
}

输出:

Json objects are:::{"Data":{"A":{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}}}
Json objects are:::{"Data":{"A":[{"B":{"C":"c","D":{}},"E":{"F":"f"},"G":{"H":"h"}},{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}]}}

最佳答案

如果您没有使用外部 JSON 库的限制,那么您可以使用 net.sf.json.JSONObject 来解析您的 JSON 字符串,它将接受带有重复键的 JSON。它将通过将重复值存储到数组中来保留它们。

JSONObject jsonObject = JSONObject.fromObject( "{\"Data\": {\"A\": {\"B\": {\"C\": \"c\",\"D\": {}},\"E\": {\"F\": \"f\"},\"G\": {\"H\": \"h\"}},\"A\": {\"B\": {\"C\": \"x\",\"D\": {}},\"E\": {\"F\": \"y\"},\"G\": {\"H\": \"z\"}}}}" );
System.out.println( "net.sf.json.JSONObject: " + jsonObject );

关于java - 使用重复键解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50582743/

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