简体   繁体   中英

Java String.valueOf returns null string

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"
}
]

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);
 }
    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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM