gpt4 book ai didi

java - 如何在 Java 中将一个 JSON 字符串拆分为两个 JSON 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:16 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com