Throwing exceptions allowed by JSON with Java

I have a JSON string :

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

      

In Java I am trying 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 am trying to get the value of a field _id

:

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

      

but meet the following exception:

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

      

Also, if I show the value of the field in the console:

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

      

I get:

print value -  _id: -1

      

in the console.

I saw this post:

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

But it doesn't help me.

What? I do not understand?

+3


source to share


4 answers


You need to use a method .toString()

to convert Long to String.

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

      

Link :



Returns a String object representing this long value.

Also, the reason is println

printing the value to the console because it PrintStream.println

has an overload that takes Object

and then calls its method toString

.

+2


source


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

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

      

jsonObject.get("_id")

returns - as indicated by the error - a java.lang.Long

and you later added it to String

.

You can solve this problem, for example:

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

      

There (String)

is no conversion in Java , but downcast. Since a is String

not a subclass Long

, this would be an error. However, you can call .toString()

that converts Long

to text representation.




Cause:

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

      

works because if you "add" an object to a string, the method toString

is called automatically. Implicitly you wrote:

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

      

+2


source


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

.

If you want the string to use jsonObject.getString("_id").

+1


source


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

Its value is -1 (versus "-1"), so it's actually a Long, not a String.

However, if you need a string, you can use it via

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

      

+1


source







All Articles