gpt4 book ai didi

Android 创建一个 Json 字符串

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

我正在尝试在 Android 应用程序中创建一个 JSON 字符串。

    JSONArray jArrayFacebookData = new JSONArray();
JSONObject jObjectType = new JSONObject();

// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");

jArrayFacebookData.put(jObjectType);

// 2nd array for user information
JSONObject jObjectData = new JSONObject();


// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);

jArrayFacebookData.put(jObjectData);

创建这样的字符串

[
{
"type":"facebook_login"
},
{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206@gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]

我想创建一个像这样的 JSON 字符串

[
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206@gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]

最佳答案

JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();

// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");

jArrayFacebookData.put("system", jObjectType);

// 2nd array for user information
JSONObject jObjectData = new JSONObject();


// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);

jArrayFacebookData.put("data", jObjectData);

这将为您提供 jsonObject,但不会提供数组,我看不出使用 JSONArray 有任何意义。在这种情况下,JSONObject 更好。您将看到以下输出为字符串

{
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206@gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
}

关于Android 创建一个 Json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079116/

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