[英]How to read numbers from JSON with different class in the same field?
我正在嘗試從JSON文件中提取“情感”值。
{
"id": 1140,
"company": "Barclays",
"title": "Barclays set to name former JPMorgan banker Staley as new CEO",
"sentiment": 0.000
},
{
"id": 1141,
"company": "Kingfisher",
"title": "Kingfisher share price slides on cost to implement new strategy",
"sentiment": -0.786
},
如果我沒記錯的話,“-0.786”是雙精度字符,而“ 0.000”是一個長整數。前幾個輸出是成功的,直到:
Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
我對此很陌生,是否有解決此問題的方法或需要參考的內容?
碼:
public static void printScore(String data)
{
JSONParser parser = new JSONParser();
String link = data;
try {
JSONArray a = (JSONArray) parser.parse(new FileReader(link));
for (Object o:a){
JSONObject jsonObject = (JSONObject) o;
double score = (double) jsonObject.get("sentiment");
//DecimalFormat df = new DecimalFormat(#.###);
System.out.format("%.3f",score);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
試試這個代碼:
package com.test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class Json {
public static void main(String[] args) {
printScore("test.json");
}
public static void printScore(String data) {
JsonParser parser = new JsonParser();
String link = data;
JsonArray a;
try {
a = (JsonArray) parser.parse(new FileReader(link));
for (Object o : a) {
JsonObject jsonObject = (JsonObject) o;
double score = jsonObject.get("sentiment").getAsDouble();
System.out.format("%.3f", score);
}
} catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.