Android创建一个Json String

前端之家收集整理的这篇文章主要介绍了Android创建一个Json String前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 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","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",display_photo_url);

    jArrayFacebookData.put("data",jObjectData);

这将给你jsonObject,但不是数组,我没有看到使用JSONArray的任何意义.在这种情况下,JSONObject更好.您将看到以下输出为String

{
   "system":{
      "type":"facebook_login"
   },"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
   }
}
原文链接:https://www.f2er.com/android/316659.html

猜你在找的Android相关文章