0

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"
}
]
3
  • For a start you need to actually get the values out of the json - it seems from your console output that you dont. Commented Sep 11, 2014 at 19:01
  • Can you see you see your problem ? try this if it works String idValue = String.valueOf(jsonObject.get("Deptid")); Commented Sep 11, 2014 at 19:12
  • @meirshapiro really using == for string ... use .equals for strings Commented Sep 11, 2014 at 19:14

2 Answers 2

1

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);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

As i said ... ! Use .equals check the answer if it works
0
    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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.