2017-02-18 87 views
0

如何向JSONObject插入/添加數據 正試圖創建包含以下數據集的JSONObject。以某種格式插入數據ro_jsonobject

{ 
    "feature": "testFeature", 
    "scenario": [{ 
     "name": "Add numbers", 
     "tag": "@test" 
    }, { 
     "name": "Delete numbers", 
     "tag": "@test123" 
    }] 

} 

我不知道如何proceed.please幫助。

Collection<JSONObject> items = new ArrayList<JSONObject>(); 
    JSONArray array1 = new JSONArray(); 
    JSONObject item1 = new JSONObject(); 
    item1.put("scenario", array1); 

回答

2

試試這個:

JSONObject main = new JSONObject(); 
main.put("feature","testFeature"); 
JSONArray scenario = new JSONArray(); 
JSONObject s1 = new JSONObject(); 
s1.put("name","Add numbers"); 
s1.put("tags","@test"); 
JSONObject s2 = new JSONObject(); 
s2.put("name","Delete numbers"); 
s2.put("tags","@test123"); 
scenario.add(s1); 
scenario.add(s2); 
main.put("scenario", scenario); 
1
package demo; 
import com.alibaba.fastjson.JSONArray; 
import com.alibaba.fastjson.JSONObject; 

public class Demo { 

    public static void main(String[] args) { 

     JSONObject json = new JSONObject(); 
     json.put("feature", "testFeature"); 
     JSONArray jsonArray = new JSONArray(); 
     JSONObject jsonArray_json1 = new JSONObject(); 
     jsonArray_json1.put("name", "Add numbers"); 
     jsonArray_json1.put("tag", "@test"); 
     jsonArray.add(jsonArray_json1); 
     JSONObject jsonArray_json2 = new JSONObject(); 
     jsonArray_json2.put("name", "Delete numbers"); 
     jsonArray_json2.put("tag", "@test123"); 
     jsonArray.add(jsonArray_json2); 
     json.put("scenario", jsonArray); 
     System.out.println(json); 

    } 
}