作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个 JSON
对象,如下所示:
{
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"user":{
"pk":17,
"username":"user1",
"email":"user1@gmail.com",
"first_name":"",
"last_name":""
}
}
我试图从中获取两个 JSON
对象; token 和用户。我尝试了两种不同的方法,但都失败了:
//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());
jsonObjectRoot = new JSONObject(response.body().string());
谁能告诉我如何将其拆分为两个 JSON
对象?
最佳答案
你可以这样拆分:
// 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":"user1@gmail.com","username":"user1"}}
关于java - 如何在 Java 中将一个 JSON 字符串拆分为两个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55191982/
我是一名优秀的程序员,十分优秀!