如何使用String创建JSON对象?

时间:2013-11-21 09:34:11

标签: java android json

我想使用String创建一个JSON对象。

示例: JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}

为了创建上面的JSON我正在使用它。

String message;
JSONObject json = new JSONObject();

json.put("test1", "value1");

JSONObject jsonObj = new JSONObject();

jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);

message = json.toString();
System.out.println(message);

我想知道如何创建一个包含JSON数组的JSON。

以下是JSON示例。

{
  "name": "student",
   "stu": {
    "id": 0,
    "batch": "batch@"
  },
  "course": [
    {
      "information": "test",
      "id": "3",
      "name": "course1"
    }
  ],
  "studentAddress": [
    {
      "additionalinfo": "test info",
      "Address": [
        {
          "H.No": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality",
           "id":33          
        },
        {
           "H.No": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality", 
           "id":33                   
        },        
        {
           "H.No": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality", 
           "id":36                   
        }
      ],
"verified": true,
    }
  ]
}

感谢。

4 个答案:

答案 0 :(得分:147)

JSONArray可能就是您想要的。

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

答案 1 :(得分:3)

与公认的答案相反,该文档说,对于 JSONArray(),您必须使用put(value)add(value)

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

(Android API19-27。Kotlin1.2.50)

答案 2 :(得分:1)

如果使用gson.JsonObject,则可以得到类似的内容:

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)

答案 3 :(得分:0)

Underscore-java 可以从对象创建 json。

    String message = U.objectBuilder()
            .add("course", U.arrayBuilder()
                    .add(U.objectBuilder()
                            .add("id", 3)
                            .add("information", "test")
                            .add("name", "course1")
                    ))
            .add("name", "student")
            .toJson();
    System.out.println(message);

// {
//   "course": [
//     {
//       "id": 3,
//       "information": "test",
//       "name": "course1"
//     }
//   ],
//   "name": "student"
// }