尝试从 java 中的 JSON 文件中读取整数

Trying to read Integer from JSON file in java

我正在尝试读取 JSON 文件以创建新对象。我可以读取其中的所有字符串,但在尝试读取 int 时抛出 ClassCastException。这是 JSON 文件。

{"id1" : "string1", 
 "id2": "string2",            
 "id3": 100.0
}   

这里是 java 代码。

public static Aparelho novoAparelho(JSONObject obj) {

    Aparelho ap = null;

        String tipe = (String) obj.get("id1");
        String name = (String) obj.get("id2");


        if(tipe.equals("anyString")) {
            int pot = (int) obj.get("id3");
            ap = new SomeObject(name, pot);
        }

    return ap;
}

它抛出。 线程 "main" java.lang.ClassCastException 中的异常:java.lang.Double 无法转换为 java.lang.Integer

整数没有小数点。

您应该解析为 int 而不是转换为 int。

例如:

if (tipe.equals("anyString")) {
    String pot = obj.get("id3");
    int x = Integer.parseInt(pot);
    ap = new SomeObject(name, x);
}

先投给double

int pot = (int) (double) obj.get("id3");
ap = new SomeObject(name, pot);

令人困惑的是,共有三种类型的转换:

  • 那些转换原语值的
  • 那些改变引用类型的
  • 装箱和拆箱的那些

在这种情况下,您有一个 Object(实际上是一个装箱的 Double),并且您需要一个原始 int。您不能使用相同的转换进行拆箱和转换,因此我们需要两个转换:第一个从 Objectdouble(拆箱),一个从 doubleint(转换)。

因为您知道该字段应该是 int,您可以利用 JSONObject api 为您处理解析:

        if(tipe.equals("anyString")) {
            int pot = obj.getInt("id3");
            ap = new SomeObject(name, pot);
        }

这比强制转换方法更可靠——如果有人更改传递给您的 json,则接受的答案可能会中断。