我正在尝试解析 Java 中具有重复键的嵌套 Json
。我遇到过其他类似的问题,但无法找到解决方案。我尝试了一种使用 Jackson 流 API 的方法,但它只打印第一个键的值并忽略第二个重复键。请帮忙。提前致谢。
代码:
public class JacksonJson {
public static void main(String args[]) throws IOException {
/
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(new File("a.json"));
parser.nextToken();
while (parser.nextToken() != JsonToken.END_OBJECT) { //loop until "}"
String fieldName = parser.getCurrentName();
if (fieldName.equals("A")) {
parser.nextToken();
System.out.println("Value : " + parser.getText());
}
/*else { // unexpected token, generate error
throw new IOException("Unrecognized field '"+fieldName+"'");
}*/
}
parser.close();
}
}
Json 文件:
{
"Data": {
"C": {
"S": {
"M": {},
"A": "first"
}
},
"C": {
"S": {
"M": {}
"A": "Second",
}
}
}
}
最佳答案
A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
许多 JSON 库提供将 json 映射到对象的功能。想想看,如果名称不唯一,它们应该如何工作?
当然,您可以尝试自己解析它并在内部将其重命名为 C1、C2...,但禁止此类情况要容易得多。
关于java - 解析具有重复键的 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50578992/