Roy Hinkley
Roy Hinkley

Reputation: 10641

Exception casting valid JSON with Java

I have a JSON string:

{
    "_id": -1,
    "create_date": 0,
    "update_date": 0,
    "description": "test",
    "active": true
}

In Java, I try to parse it using org.json.simple.parser.JSONParser :

JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(phoneJSON);

I try to retrieve the _id field value:

String s_id = ((String) jsonObject.get("_id"));

but encounter the following exception:

java.lang.Long cannot be cast to java.lang.String

Furthermore, if I display the field value in the console:

System.out.println("print value -  _id: "+jsonObject.get("_id"));

I get:

print value -  _id: -1

output in the console.

I have seen this post:

java.lang.Long cannot be cast to java.lang.String

But is does not help me.

What am I not understanding?

Upvotes: 3

Views: 461

Answers (4)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

The problem is not in the parsing process. But in the casting process of the following line:

String s_id = ((String) jsonObject.get("_id"));

jsonObject.get("_id") returns - as specified by the error - a java.lang.Long, and you later cast it to String.

You can solve this, for instance with:

String s_id = jsonObject.get("_id").toString();

In Java the (String) is not a conversion, but a downcast. Since a String is not a subclass of Long, it will error. You can however call .toString() that will transform the Long in a textual representation.


The reason:

System.out.println("print value -  _id: "+jsonObject.get("_id"));

works is because if you "add" an object to a string, the toString method is called automatically. Implicitly you have written:

System.out.println("print value -  _id: "+Objects.toString(jsonObject.get("_id")));

Upvotes: 2

Robert
Robert

Reputation: 452

The value of _id is correctly identified as Long (-1 in the example) when you use jsonObject.get("_id").

If you want a String use jsonObject.getString("_id").

Upvotes: 1

Ali Gajani
Ali Gajani

Reputation: 15091

You have to use the .toString() method to convert Long to String.

String strLong = Long.toString(jsonObject.get("_id")));

Reference:

Returns a String object representing this Long's value.

Also, the reason println outputs the value in the console is because PrintStream.println has an overload that takes an Object, and then calls its toString method.

Upvotes: 2

43iscoding
43iscoding

Reputation: 21

Why do you except the "_id" field to be a string?

Its value is -1 (opposed to "-1") so it is actually a Long instead of String.

However, if you need string, you can cast it via

String s_id = String.valueOf(jsonObject.get("_id"));

Upvotes: 1

Related Questions