这是我正在使用的 JSON 文件
{"sentiment":
{"document":
{
"label": "positive",
"score": 0.53777
}
}
}
我需要访问label
和score
中的值。使用java。我怎样才能做到这一点?
在下面找到我现在使用的代码:
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = new JSONObject();
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
System.out.println(test);
} catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
为什么将值打印为null
。
最佳答案
您可能想看看 JacksonXml 的 json 解析。
现在的问题是您没有使用 parser.parse(...)
返回的 JsonObject。
相反,您可以对刚刚创建的对象使用 get 方法。这当然意味着你没有得到你想要的值(value)。
关于java - 使用 JAVA 访问 JSON 文件中的预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52443290/