繁体   English   中英

如何从同一字段中具有不同类的JSON中读取数字?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM