132

如何在 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();
}

有任何想法吗。谢谢

4

11 回答 11

336

使用以下代码:

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);
于 2013-07-23T12:31:12.803 回答
31
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;
    }
于 2013-11-22T09:24:01.403 回答
6
 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());
于 2013-07-23T12:30:47.547 回答
4

您可以创建 aa 方法并将参数传递给它并获取 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;
      }

我希望这能帮到您。

于 2013-07-23T12:42:04.157 回答
3

这是一个不需要 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。

如果你想避免再次尝试捕获(不是很推荐,但如果你能保证格式正确的 json 字符串就可以了),你可以这样做:

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

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

干杯。

于 2017-01-26T01:54:14.307 回答
2

现在回答为时已晚,抱歉,创建以下正文:

{
    "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;
    }
于 2021-01-31T07:26:39.860 回答
1

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

  1. 使用 GSON 库:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
    
  2. 传递 json 数组。这将被自动字符串化。这个选项对我来说非常有效。

于 2015-05-28T13:53:17.120 回答
1
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);
于 2016-05-19T16:00:10.547 回答
0
            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.
于 2019-06-25T01:51:40.763 回答
0
  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();
        }
    });
}
于 2019-08-10T15:06:28.880 回答
-2

您应该使用 JSONObject.put 方法

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

于 2019-09-10T23:02:08.227 回答