Nabat persa:
Tengo un JSON
objeto de la siguiente manera:
{
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"user":{
"pk":17,
"username":"user1",
"email":"[email protected]",
"first_name":"",
"last_name":""
}
}
Estoy tratando de conseguir dos JSON
objetos de ella; token y usuario. He tratado de dos maneras diferentes, pero ambos están fallando:
//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());
jsonObjectRoot = new JSONObject(response.body().string());
Podría alguien por favor hágamelo saber cómo podría dividir esto a dos JSON
objetos?
Michael Ziober:
Se puede dividir de esta manera:
// 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);
imprime el código de seguridad:
Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}
User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"[email protected]","username":"user1"}}