How to create JSON Object using String?

后端 未结 3 1796
悲哀的现实
悲哀的现实 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:13

    In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

    https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

    (Android API 19-27. Kotlin 1.2.50)

    0 讨论(0)
  • 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"}
    
    0 讨论(0)
  • 2020-12-02 06:29

    If you use the gson.JsonObject you can have something like that:

    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
    
    0 讨论(0)
提交回复
热议问题