Reputation: 3696
I have a json input, I need to assign one of the value from json to int. How can I do it?
1) I tried this way, is there any better approach?
String idValue = String.valueOf(jsonObject.get("id"));
System.out.println("IDValue 1 is-->"+jsonObject.get("id"));
System.out.println("IDValue 2 is-->"+idValue);
int id = 0;
if(idValue != null){
System.out.println("IDValue 3 is-->"+idValue);
id = Integer.parseInt(idValue);
}
Console output:
IDValue 1 is-->null
IDValue 2 is-->null
IDValue 3 is-->null
I am using Java1.7 and json simple jar
2) I dont have any input value for id in json. Here I am not sure why it enters inside if condition.
When I do this: It enters inside if condition:
if(idValue.equals("null")){
System.out.println("Entered inside");
}
output:
IDValue 1 is-->null
IDValue 2 is-->null
IDValue 3 is-->null
Entered inside
My Json:
[
{
"Company":"BEG22",
"Account":"1004",
"Deptid":"13"
},
{
"Company":"BEG3",
"Account":"1002",
"Deptid":"24"
}
]
Upvotes: 0
Views: 886
Reputation: 3696
Here is the reason: Implementation of String.valueOf is:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So finally:
if(!idValue.equals("null") ){
System.out.println("IDValue 2 is-->"+idValue);
id = Integer.parseInt(idValue);
}
Upvotes: 1
Reputation: 6816
String idValue = String.valueOf(jsonObject.get("Deptid"));
System.out.println("IDValue 1 is-->"+jsonObject.get("Deptid"));
System.out.println("IDValue 2 is-->"+idValue);
int id = 0;
if("null".equals(idValue)){
System.out.println("IDValue 3 is-->"+idValue);
id = Integer.parseInt(idValue);
}
A few things I change try this if it works ...
Upvotes: 0