[英]Access intended values in JSON file using JAVA
這是我正在使用的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方法。 當然,這意味着您不會獲得想要的價格。
嘗試使用以下代碼( JSONObject jsonObject = (JSONObject) object
而不是JSONObject jsonObject = new JSONObject();
),因為您根本沒有使用對象,只需創建新的空JSONObject。
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
JSONObject documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
System.out.println(label);
float score = (float) documentobject.get("score");
System.out.println(score );
}catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
你必須要使用的object
中創建Object object = parser.parse(new FileReader("output_nlu_sentiment.json"));
在創建jsonObject
為此,您可以查看下面的代碼:
Object object = parser
.parse(new FileReader("file2.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
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");
您將在控制台上得到positive
印刷。
您應該在para'sentimentobject'中看到內容,強制轉換為JSONObject類無法獲取所需的值。
我更喜歡FasterXML Jackson支持將JSON解析為普通的舊Java對象(POJO)。 這些POJO通常稱為數據傳輸對象(DTO),為您提供一種將JSON字段轉換為相應DTO的正確類型化成員的方法。
這是執行此操作的示例方法。 由於FasterXML的實現會緩存信息以提高對象映射操作的效率,因此ObjectMapper通常在其他地方保持為靜態。
static final ObjectMapper mapper = new ObjectMapper();
這是JSON反序列化方法:
public static <T> T deserializeJSON(
final ObjectMapper mapper, final InputStream json,
final Class<T> clazz)
throws JsonParseException, UnrecognizedPropertyException,
JsonMappingException, IOException
{
final String sourceMethod = "deserializeJSON";
logger.entering(sourceClass, sourceMethod);
/*
* Use Jackson support to map the JSON into a POJO for us to process.
*/
T pojoClazz;
pojoClazz = mapper.readValue(json, clazz);
logger.exiting(sourceClass, sourceMethod);
return pojoClazz;
}
假設我有一個名為FooDTO的類,該類具有適當的Jackson批注/獲取器/設置器(請注意,您必須始終提供默認的空公共構造函數),您可以執行以下操作:
FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);
反序列化引發了一些不同的異常(所有這些異常均具有IOException作為其父類),您需要處理這些異常或將其拋出給調用者。
除了在注釋和其他答案中解決的修正問題外,這里還包括您可以從中受益的其他一些更改:
不必使用將在下一行中重寫的新實例來初始化JSONObjects。
您可以使用getJSONObject()
, getString()
, getFloat()
而不是get()
,通過這種方式,您無需轉換結果。
public void parseJson() {
JSONParser parser = new JSONParser();
try
{
JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
JSONObject sentimentobject= null;
JSONObject documentobject = null;
sentimentobject= jsonObject.getJSONObject("sentiment");
documentobject= sentimentobject.getJSONObject("document");
String label = documentobject.getString("label");
float score = documentobject.getFloat("score");
String output = String.format("Label: %s Score: %f", label, score);
System.out.println(output);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
同樣對於這類對象,屬性名稱可以用作對象屬性,我建議您看一下Gson庫。 在將json建模為POJO的組合之后,解析需要1行代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.