How to create JSON Object using String?

后端 未结 3 1809
悲哀的现实
悲哀的现实 2020-12-02 05:58

I want to create a JSON Object using String.

Example : JSON {\"test1\":\"value1\",\"test2\":{\"id\":0,\"name\":\"testName\"}}

In order to creat

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 06:29

    JSONArray may be what you want.

    String message;
    JSONObject json = new JSONObject();
    json.put("name", "student");
    
    JSONArray array = new JSONArray();
    JSONObject item = new JSONObject();
    item.put("information", "test");
    item.put("id", 3);
    item.put("name", "course1");
    array.add(item);
    
    json.put("course", array);
    
    message = json.toString();
    
    // message
    // {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
    

提交回复
热议问题