Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse JSON into an int?

Tags:

I have Parsed some JSON data and its working fine as long as I store it in String variables.

My problem is that I need the ID in an int varibable and not in String. i have tried to make a cast int id = (int) jsonObj.get("");

But it gives an error message that I cannot convert an object to an int. So I tried to convert by using:

String id = (String) jsonObj.get("id"); int value = Integer.parseInt(id); 

But also that is not working. What is wrong. How is JSON working with int? My strings are working just fine its only when I try to make them as an int I get problems.

Here is my code :

public void parseJsonData() throws ParseException {          JSONParser parser = new JSONParser();         Object obj = parser.parse(jsonData);         JSONObject topObject = (JSONObject) obj;         JSONObject locationList = (JSONObject) topObject.get("LocationList");         JSONArray array = (JSONArray) locationList.get("StopLocation");         Iterator<JSONObject> iterator = array.iterator();          while (iterator.hasNext()) {              JSONObject jsonObj = (JSONObject) iterator.next();             String name  =(String) jsonObj.get("name");             String id = (String) jsonObj.get("id");             Planner.getPlanner().setLocationName(name);             Planner.getPlanner().setArrayID(id);           }      } 
like image 635
Josef Avatar asked Mar 29 '13 08:03

Josef


People also ask

Can JSON value be int?

JSON NumbersNumbers in JSON must be an integer or a floating point.

How do you parse JSON?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Can Int be key in JSON?

JSON only allows key names to be strings. Those strings can consist of numerical values.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.


Video Answer


1 Answers

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id")); 

or better and more directly the getInt method :

int id = jsonObj.getInt("id"); 
like image 69
Denys Séguret Avatar answered Sep 19 '22 19:09

Denys Séguret