Long 不能转换为 String

Long cannot be cast to String

我想知道为什么我会在以下代码中遇到以下异常:

public class AAA {

    public static void main(String [] args) throws ParseException{
        AAA a= new AAA();
    }


    public AAA() throws ParseException{
        String str = "{\"a\":1,\"b\":\"2\",\"c\":\"3\"}";
        JSONParser content_parser = new JSONParser();
        Object objMessage_Content = content_parser.parse(str);
        System.out.println(objMessage_Content);
        JSONObject jsonObjectMessage_Content = (JSONObject) objMessage_Content;
        System.out.println(jsonObjectMessage_Content);

        String a = (String) jsonObjectMessage_Content.get("a");
        String b = (String) jsonObjectMessage_Content.get("b");
        String c = (String) jsonObjectMessage_Content.get("c");
        String d = (String) jsonObjectMessage_Content.get("d");

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
    }
}

我遇到了这个异常:

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
    at test.AAA.<init>(AAA.java:39)
    at test.AAA.main(AAA.java:11)

看起来键 "a" 的值是数字 - \"a\":1。 因此 jsonObjectMessage_Content.get("a") returns a Long 不能转换为 String.

您可以将其替换为

String a = String.valueOf(jsonObjectMessage_Content.get("a"));

您可以类似地替换所有 4 个赋值,以处理其他键具有非字符串值的情况。

您也可以将其替换为:

String a = jsonObjectMessage_Content.get("a")+"";
String b = jsonObjectMessage_Content.get("b")+"";
String c = jsonObjectMessage_Content.get("c")+"";
String d = jsonObjectMessage_Content.get("d")+"";

简直快~