Search code examples
javajsonorg.json

How to Split a JSON string to two JSON objects in Java


I have a JSON object as follows:

{  
   "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
   "user":{  
      "pk":17,
      "username":"user1",
      "email":"[email protected]",
      "first_name":"",
      "last_name":""
   }
}

I am trying to get two JSON object from it; token and user. I have tried two different ways but both are failing:

//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());

jsonObjectRoot = new JSONObject(response.body().string());

Could any one please let me know how I could split this to two JSON objects?


Solution

  • You can split it this way:

    // source object
    JSONObject sourceObject = new JSONObject(sourceJson);
    
    String tokenKey = "token";
    // create new object for token
    JSONObject tokenObject = new JSONObject();
    
    // transplant token to new object
    tokenObject.append(tokenKey, sourceObject.remove(tokenKey));
    // if append method does not exist use put
    // tokenObject.put(tokenKey, sourceObject.remove(tokenKey));
    
    System.out.println("Token object => " + tokenObject);
    System.out.println("User object => " + sourceObject);
    

    Above code prints:

    Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}
    User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"[email protected]","username":"user1"}}