JSON Simple: integer parsing

I have a problem with parsing JSON integer in my REST service. Parsing String and double type work fine

AT:

JSONParser parser = new JSONParser();
Object obj = null;
try {
    obj = parser.parse(input);
} catch (ParseException e) {
    e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;   

//---------------
String uName = (String) jsonObject.get("userName");
double iPrice = (Double) jsonObject.get("itemPrice");

Does not work:

int baskId = (Integer) jsonObject.get("basketId");

I tried converting the basketIdbasket to String into my class, and then it functions fine, so the code is fine and the link works, however, when I return it back to int, I get 500 server errors. I use it to create a new basket with some numerical identifier, so I use the @POST annotation, and the JSON in the payload looks like this:

{"basketId":50}

I do not understand...

EDIT: I get this ... JSON simple only accepts larger types of Java primitives, so integer and float are no-no

+4
3

jsonObject.get("basketId"); Long

, Long casting  (Long)jsonObject.get("basketId");

Integer, inetger

((Long)jsonObject.get("basketId")).intValue()
+5

String, - :

String x = "10";
int y = (int) x;

String x = "10";
int y = Integer.valueOf(x);
0

Instead: int baskId = (Integer) jsonObject.get ("basketId");

Usage: int baskId = jsonObject.getInt ("basketId");

In the official documentation: http://www.json.org/javadoc/org/json/JSONObject.html#getInt(java.lang.String)

0
source

Source: https://habr.com/ru/post/1583742/


All Articles