Android- 创建 JSON 数组和 JSON 对象

Posted

技术标签:

【中文标题】Android- 创建 JSON 数组和 JSON 对象【英文标题】:Android- create JSON Array and JSON Object 【发布时间】:2013-07-22 12:20:32 【问题描述】:

如何在 android 中创建具有这种格式的 JSON: 由于我将传递的 API 将解析 JsonArray 然后解析对象。 或者如果只是传递一个json对象可以吗?因为每次服务调用我只需插入 1 个事务。


    "student": [
        
            "id": 1,
            "name": "John Doe",
            "year": "1st",
            "curriculum": "Arts",
            "birthday": 3/3/1995
        ,
        
            "id": 2,
            "name": "Michael West",
            "year": "2nd",
            "curriculum": "Economic",
            "birthday": 4/4/1994
        
    ]

我所知道的只是 JSONObject。 喜欢这个。

JSONObject obj = new JSONObject();
try 
    obj.put("id", "3");
    obj.put("name", "NAME OF STUDENT");
    obj.put("year", "3rd");
    obj.put("curriculum", "Arts");
    obj.put("birthday", "5/5/1993");
 catch (JSONException e) 
    // TODO Auto-generated catch block
    e.printStackTrace();

任何想法。谢谢

【问题讨论】:

reference link 将 JSONObject 放入 JSONArray 以实现发布的格式.. 看看JSONArray类developer.android.com/reference/org/json/JSONArray.html @ChintanKhetiya :你救了我的一天,先生。调试器:) 【参考方案1】:

使用以下代码:

JSONObject student1 = new JSONObject();
try 
    student1.put("id", "3");
    student1.put("name", "NAME OF STUDENT");
    student1.put("year", "3rd");
    student1.put("curriculum", "Arts");
    student1.put("birthday", "5/5/1993");

 catch (JSONException e) 
    // TODO Auto-generated catch block
    e.printStackTrace();


JSONObject student2 = new JSONObject();
try 
    student2.put("id", "2");
    student2.put("name", "NAME OF STUDENT2");
    student2.put("year", "4rd");
    student2.put("curriculum", "scicence");
    student2.put("birthday", "5/5/1993");

 catch (JSONException e) 
    // TODO Auto-generated catch block
    e.printStackTrace();



JSONArray jsonArray = new JSONArray();

jsonArray.put(student1);
jsonArray.put(student2);

JSONObject studentsObj = new JSONObject();
    studentsObj.put("Students", jsonArray);



String jsonStr = studentsObj.toString();

    System.out.println("jsonString: "+jsonStr);

【讨论】:

完美的例子!【参考方案2】:
public JSONObject makJsonObject(int id[], String name[], String year[],
            String curriculum[], String birthday[], int numberof_students)
            throws JSONException 
        JSONObject obj = null;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < numberof_students; i++) 
            obj = new JSONObject();
            try 
                obj.put("id", id[i]);
                obj.put("name", name[i]);
                obj.put("year", year[i]);
                obj.put("curriculum", curriculum[i]);
                obj.put("birthday", birthday[i]);

             catch (JSONException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            
            jsonArray.put(obj);
        

        JSONObject finalobject = new JSONObject();
        finalobject.put("student", jsonArray);
        return finalobject;
    

【讨论】:

感谢这个简单的方法。【参考方案3】:
 JSONObject obj = new JSONObject();
            try 
                obj.put("id", "3");
                obj.put("name", "NAME OF STUDENT");
                obj.put("year", "3rd");
                obj.put("curriculum", "Arts");
                obj.put("birthday", "5/5/1993");

             catch (JSONException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            
             JSONArray js=new JSONArray(obj.toString());
             JSONObject obj2 = new JSONObject();
             obj2.put("student", js.toString());

【讨论】:

我假设 'JSONObject obj2 = new JSONObject(); 中的 'obj' obj.put("学生", js.toString());'是 'obj2' 吗?【参考方案4】:

您可以创建一个方法并将参数传递给它并获取 json 作为响应。

  private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException 
        JSONObject json = null;
        json = new JSONObject("\"" + "Name" + "\":" + "\"" + Name+ "\""
            + "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
            + "\":" + "\"" + curriculum+ "\"" + "");
        return json;
      

希望对你有所帮助。

【讨论】:

【参考方案5】:

这是一个更简单(但不是那么短)的版本,不需要 try-catch:

Map<String, String> data = new HashMap<>();
data.put("user", "mark@facebook.com");
data.put("pass", "123");

JSONObject jsonData = new JSONObject(data);

如果你想在字段中添加一个jsonObject,你可以这样做:

data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));

不幸的是,由于 put() 方法,它需要一个 try-catch。

如果你想避免再次try-catch(不是很推荐,但如果你能保证格式正确的json字符串也可以),你可以这样做:

data.put("socialMedia", " 'facebookId': '1174989895893400' ");

你可以对 JsonArrays 等做同样的事情。

干杯。

【讨论】:

【参考方案6】:

现在回答太晚了,很抱歉,创建以下正文:


    "username": "ًRajab",
    "email": "rajab.mohammadi@gmail.com",
    "phone": "+93767626554",
    "password": "123asd",
    "carType": "600fdcc646bc6409ae97e2ab",
    "fcmToken":"lljlkdsajfljasldfj;lsa",
    "profilePhoto": "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg",
    "documents": 
        "DL": [
            
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            
        ],
        "Registration": [
            
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            
        ],
        "Insurance":[
              
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            
        ],
         "CarInside":[
              
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            
        ],
         "CarOutside":[
              
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            
        ]
    

您可以像下面的代码一样动态创建:

JSONObject jsonBody = new JSONObject();
try 
    jsonBody.put("username", userName);
    jsonBody.put("email", email);
    jsonBody.put("phone", contactNumber);
    jsonBody.put("password", password);
    jsonBody.put("carType", carType);
    jsonBody.put("fcmToken", "lljlkdsajfljasldfj;lsa");
    jsonBody.put("profilePhoto", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg");

    JSONObject document = new JSONObject();

    try 
        document.put("DL", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Registration", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Insurance", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarInside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarOutside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
     catch (JSONException e) 
        e.printStackTrace();
    

    jsonBody.put("documents", document.toString());

    Log.i("MAHDI", "Hello: Mahdi: Data: " + jsonBody);
 catch (JSONException e) 
    e.printStackTrace();

以及createDocument方法代码:

public JSONArray createDocument(String id, String imageUrl) 

    JSONObject dlObject = new JSONObject();
    try 
        dlObject.put("_id", id);
        dlObject.put("uriPath", imageUrl);
     catch (JSONException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    
    JSONArray dlArray = new JSONArray();
    dlArray.put(dlObject);

    return dlArray;
    

【讨论】:

【参考方案7】:

一直在努力解决这个问题,直到我找到答案:

    使用 GSON 库:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
    

    传递 json 数组。这将被自动字符串化。这个选项非常适合我。

【讨论】:

【参考方案8】:
JSONObject jsonResult = new JSONObject();
try 
  jsonResult.put("clave", "valor");
  jsonResult.put("username", "iesous");
  jsonResult.put("password", "1234");

 catch (JSONException e) 
  // TODO Auto-generated catch block
 e.printStackTrace();


Log.d("DEV","jsonResult->"+jsonResult);

【讨论】:

你应该添加一些叙述来解释你的答案并改进格式。【参考方案9】:
            Map<String, String> params = new HashMap<String, String>();

            //** Temp array
            List<String[]> tmpArray = new ArrayList<>();
            tmpArray.add(new String[]"b001","book1"); 
            tmpArray.add(new String[]"b002","book2"); 

            //** Json Array Example
            JSONArray jrrM = new JSONArray();
            for(int i=0; i<tmpArray.size(); i++)
                JSONArray jrr = new JSONArray();
                jrr.put(tmpArray.get(i)[0]);
                jrr.put(tmpArray.get(i)[1]);
                jrrM.put(jrr);
            

           //Json Object Example
           JSONObject jsonObj = new JSONObject();
            try 
                jsonObj.put("plno","000000001");                   
                jsonObj.put("rows", jrrM);

            catch (JSONException ex)
                ex.printStackTrace();
               


            // Bundles them
            params.put("user", "guest");
            params.put("tb", "book_store");
            params.put("action","save");
            params.put("data", jsonObj.toString());

           // Now you can send them to the server.

【讨论】:

【参考方案10】:
  public void DataSendReg(String picPath, final String ed2, String ed4, int bty1, String bdatee, String ed1, String cno, String address , String select_item, String select_item1, String height, String weight) 

      final ProgressDialog dialog=new ProgressDialog(SignInAct.this);
      dialog.setMessage("Process....");
      AsyncHttpClient httpClient=new AsyncHttpClient();
      RequestParams params=new RequestParams();
      File pic = new File(picPath);
      try 
          params.put("image",pic);
       catch (FileNotFoundException e) 
          e.printStackTrace();
      
      params.put("height",height);
      params.put("weight",weight);
      params.put("pincode",select_item1);
      params.put("area",select_item);
      params.put("address",address);
      params.put("contactno",cno);
      params.put("username",ed1);
      params.put("email",ed2);
      params.put("pass",ed4);
      params.put("bid",bty1);
      params.put("birthdate",bdatee);
      params.put("city","Surat");
      params.put("state","Gujarat");


      httpClient.post(WebAPI.REGAPI,params,new JsonHttpResponseHandler()
          @Override
          public void onStart() 
              dialog.show();
          

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) 
              try 
                  String done=response.get("msg").toString();
                  if(done.equals("s")) 
                      Toast.makeText(SignInAct.this, "Registration Success Fully", Toast.LENGTH_SHORT).show();
                      DataPrefrenceMaster.SetRing(ed2);
                      startActivity(new Intent(SignInAct.this, LoginAct.class));
                      finish();
                  
                  else  if(done.equals("ex")) 
                      Toast.makeText(SignInAct.this, "email already exist", Toast.LENGTH_SHORT).show();
                  else Toast.makeText(SignInAct.this, "Registration failed", Toast.LENGTH_SHORT).show();
               catch (JSONException e) 
                  Toast.makeText(SignInAct.this, "e :: ="+e.getMessage(), Toast.LENGTH_SHORT).show();
              
          

          @Override
          public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) 
              Toast.makeText(SignInAct.this, "Server not Responce", Toast.LENGTH_SHORT).show();
              Log.d("jkl","error");
          

          @Override
          public void onFinish() 
                   dialog.dismiss();
        
    );

【讨论】:

这将有助于在您的代码中添加一些上下文解释,因为您似乎在回答错误的问题...【参考方案11】:

你应该使用 JSONObject.put 方法

https://developer.android.com/reference/org/json/JSONObject.html#put(java.lang.String,%20double)

【讨论】:

以上是关于Android- 创建 JSON 数组和 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章

Android原生json和fastjson的简单使用

如何仅将一些选定的 Json 数组和 Json 对象从 Url 解析到 android 设备

将我的 JSON 数组从 android 线程返回到类

如何在 Android 中使用 Java 和 org.json 迭代这个 JSON 数组?

Android Retrofit 数组列表中的嵌套 JSON 对象

android怎么把json转换为hashmap