创建 JSON 数组和 JSON 对象

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

有什么想法吗,谢谢

248325 次浏览
 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 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);

您可以创建一个方法并将参数传递给它,然后获得 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;
}

我希望这能帮到你。

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;
}

一直在纠结这个问题,直到我找到了答案:

  1. 使用 GSON 库:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
    
  2. Pass the json array. This will be auto stringfied. This option worked perfectly for me.

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);

这里有一个更简单(但不是很短)的版本,它不需要 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。

如果 您想避免再次尝试-catch (不是很推荐,但是如果您可以保证格式良好的 json 字符串就可以了) ,您可以这样做:

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

您可以对 JsonArray 等进行同样的操作。

干杯。

            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.
  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();
}
});
}

现在回答这个问题已经太晚了,很抱歉,因为创造了下面的主体:

{
"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;
}