简体   繁体   中英

How to read numbers from JSON with different class in the same field?

I am trying to extract "sentiment"value from JSON file.

{
  "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 :

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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