Cómo dividir una cadena JSON a dos objetos JSON en Java

Nabat persa:

Tengo un JSONobjeto de la siguiente manera:

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

Estoy tratando de conseguir dos JSONobjetos 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 JSONobjetos?

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"}}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=214680&siteId=1
Recomendado
Clasificación