JSONはJavaでオブジェクトを2にJSON文字列を分割する方法

Nabatペルシア語:

私が持ってJSON次のようにオブジェクトを:

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

私は2つの取得しようとしていますJSON、それからオブジェクトを。トークンとユーザー。私は2つの異なる方法を試してみましたが、両方が失敗しています。

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

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

いずれかの私は2つのにこれを分割することができる方法を知って聞かせてもらえJSONオブジェクト?

マイケルZiober:

あなたはそれをこのように分割することができます。

// 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);

上記のコードを印刷:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=214674&siteId=1