user2340312
user2340312

Reputation: 61

Long cannot be cast to String

I want to know why I'm getting the following exception in the following code :

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

I am getting this exception :

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)

Upvotes: 1

Views: 1635

Answers (2)

Kouichi
Kouichi

Reputation: 403

You also can replace it with:

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

simply fast~

Upvotes: 0

Eran
Eran

Reputation: 393936

It looks like the value of the key "a" is numeric - \"a\":1. Therefore jsonObjectMessage_Content.get("a") returns a Long, which can't be cast to String.

You can replace it with

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

You can replace all 4 assignments similarly to handle the cases where the other keys have non-String values.

Upvotes: 7

Related Questions