Search code examples
androidstringvariablesresponse

how do I save a part of a variable string?


I get a response but it's different for every user. I want to extract the UserID & Name. How can I do this?

The response String:

{
    "sessionkey":"f4b54dedlfkjhgdlfkjghdfslkjgh1a255242bf71597f4b35ac882f0702",
    "user" : {
        "userID" : "1",
        "name":"Test"
    }
}

I want to save 1 = (String userid) and save Test = (String name)

Thanks in advance


Solution

  • This is just a simple JSON blob, so use a JSON Parser to extract the data.

    My lib of choice is org.json.json.

    String blob = "{ origin string }";
    
    // create a new json object from the main blob
    JSONObject root = new JSONObject(blob);
    
    // extract the session key
    String sessionKey = root.getString("sessionkey");
    
    // extract the user object
    JSONObject user = root.getJSONObject("user");
    
    // extract the user id
    String userId = user.getString("userID");