难以计数json文件中的密钥

时间:2019-04-08 21:08:06

标签: java json

我很难计算json文件中包含的键的数量,特别是重复的键,因为它们只被计数一次。

我像这样打开/读取文件:

String line = "";
String fileContents = "";

try {
  reader = new BufferedReader(new FileReader(inputFile));
} catch (FileNotFoundException ex) {
  throw new LicensingException("Error: input file not found. ");

}

try {
  while ((line = reader.readLine()) != null) {
    fileContents += line;
  }
} catch (IOException ex) {
  throw new LicensingException("Error: input file could not be accessed.");
}

try {
  reader.close();
} catch (IOException ex) {
  throw new LicensingException("Error: input file could not be closed.");
}

并像这样创建JsonObject:

JsonObject jsonLicense = null;
StringReader sr = new StringReader(fileContents); 
jsonLicense = Json.createReader(sr).readObject();

完成此操作后,我继续计算对象中的键数:

  int i = 0;

  for (String key: jsonLicense.keySet()) {
    i++;
  }

但是正如我之前所说,只有当所有密钥都不相同时,当我复制一个密钥时,它们才被计数一次。

我试图从以下位置计算密钥的json文件

{"Station Name" : "Hello",
"Person in charge": "this",
"EMail": "is@an.com", 
"Machine Name": "example",
"Type of License": "Starship",
"Type of License": "All"
}

1 个答案:

答案 0 :(得分:0)

形成您的JSON,以将多个值视为这样的数组:

{
"Station Name" : "Hello",
"Person in charge": "this",
"EMail": "is@an.com", 
"Machine Name": "example",
"Types of License": ["Starship", "All"]
}

,然后计算与每个键而不是键相关的值的数量。