简体   繁体   English

Java String.valueOf返回空字符串

[英]Java String.valueOf returns null string

I have a json input, I need to assign one of the value from json to int. 我有一个json输入,我需要将json中的值之一分配给int。 How can I do it? 我该怎么做?

1) I tried this way, is there any better approach? 1)我尝试过这种方法,有没有更好的方法?

        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 我正在使用Java1.7和JSON简单jar

2) I dont have any input value for id in json. 2)我没有任何输入值的ID在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: 原因如下:String.valueOf的实现是:

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 ... 我改变了一些方法,如果可行,请尝试一下...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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