簡體   English   中英

使用序列化/ GSON將對象自動轉換為Double

[英]Object Autoconvert to Double with Serialization/GSON

在開發使用Gson序列化對象並反序列化它們的應用程序時,我遇到了一個問題。 但是,我遇到了一個問題,我無法解釋原因,一段時間后,我把問題縮小到這個SSCCE:

import com.google.gson.Gson;

/**
 * demonstrates the issue at hand
 */
public class Probs {
    public Probs () {
        //holds the byte array form of the JSON data
        byte[] info = new byte[1];

        //get the JSON for a data object and store it in the byte array
        Gson gson = new Gson();
        Data before = new Data(1);
        info = gson.toJson(before).getBytes();

        //reassemble the JSON data as a string
        String json = new String(info);
        System.out.println("JSON string: " + json);

        //reconstruct the Data object from the JSON data
        Data after = gson.fromJson(json, Data.class);

        //attempt to get the "num" value and convert it to an integer
        Object val = after.getNum();
        System.out.println("Class name: " + val.getClass().getName()); //is java.lang.Double (why isn't it java.lang.Object?)
        Integer num = (Integer)val; //produces "java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer"
        System.out.println("Number: " + num);
    }

    public static void main(String[] args) {
        new Probs();
    }
}

/**
 * holds the one piece of data
 */
class Data {
    Object num;
    public Data(int num) {
        this.num = num;
        System.out.println("Object value: " + this.num);
    }

    public Object getNum () {
        return this.num;
    }
}

我確實看過這篇文章,但它似乎沒有任何可接受的答案。 由於我在應用程序中使用它的方式,我需要讓Data對象將其數據存儲為Object,並能夠將其稍后轉換為其他類型。 當我反序列化數據對象並調用它的getNum()時,我認為應該返回一個Object(因為這是它的返回類型)。 在我的應用程序中,我需要能夠將該類型轉換為Integer。 但是,JVM似乎將Object(val)轉換為Double,因為getClass()顯示它是Double而不是Object。 然后,當我嘗試通過強制轉換將其轉換為整數時,它會失敗,因為它顯然是Double而不是Object。

我的問題是:為什么val是Double而不是Object(我不理解的是什么)?

謝謝您的幫助

問題是JSON規范,以及您正在做的事情。

JSON規范僅指定單個數字類型,可以包括小數點和小數部分:

2.4。 數字

數字的表示類似於大多數情況下使用的數字
編程語言。 數字包含整數組件
可以使用可選的減號作為前綴,其后可以是分數部分和/或指數部分。

在解析/映射JSON時,JSON解析器可以自行決定如何處理該數字類型。

在您的情況下,您的Data類已將num定義為Object 這使得Gson沒有提示您希望JSON數字類型映射到哪個特定的Java數字類型。 無論JSON中的數字是否包含小數+分數,Gson的作者都決定使用Double

當你認為一個整數可以表示為double,而不是相反的方式時,這實際上是完全有意義的。 使用單一類型而不是解析數字並確定它是int還是double提供了一致的行為。

目前還不清楚為什么你沒有在你的Data對象中使用Integer (或int )作為num ,如果那是你期望/需要的。 你聲明你需要“稍后”轉換為Integer ,這意味着對象首先可以是Integer ; 任何其他的鑄造嘗試都會失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM