[英]How to read numbers from JSON with different class in the same field?
I am trying to extract "sentiment"value from JSON file. 我正在尝试从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
},
If I am not mistaken, "-0.786" is double while "0.000" is a long.The first few output is success until : 如果我没记错的话,“-0.786”是双精度字符,而“ 0.000”是一个长整数。前几个输出是成功的,直到:
Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
I am very new in this, is there any method to solve this or anything to refer to? 我对此很陌生,是否有解决此问题的方法或需要参考的内容?
Code: 码:
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();
}
}
Try this code: 试试这个代码:
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.