Java创建(读取)比较复杂的JSON对象
使用Java创建比较复杂的JSON对象,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.ArrayList; 2 import java.util.HashMap; 3 import java.util.List; 4 5 import net.sf.json.JSONArray; 6 import net.sf.json.JSONObject; 7 8 public class testJSON { 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 HashMap<String, String> map; 12 List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); 13 for (int i = 1; i < 4; i++) { 14 map = new HashMap<String, String>(); 15 map.put("unique_id", "" + i); 16 list.add(map); 17 } 18 testJSON test = new testJSON(); 19 test.readJSON(test.createJSON(list)); 20 } 21 22 private JSONObject createJSON(List<HashMap<String, String>> list) { 23 JSONObject object = new JSONObject(); 24 JSONArray array = new JSONArray(); 25 array = JSONArray.fromObject(list); 26 27 object.put("patinent_id", "111111111"); 28 object.put("visit_id", 1); 29 object.put("file", array); 30 System.out.println("object's content----" + object.toString()); 31 return object; 32 } 33 34 private void readJSON(JSONObject object) { 35 System.out.println("patinent_id------>" 36 + object.getString("patinent_id")); 37 System.out.println("visit_id------>" + object.getInt("visit_id")); 38 JSONArray array = object.getJSONArray("file"); 39 System.out.println("These are unique_id:"); 40 for (int i = 0; i < array.size(); i++) { 41 JSONObject arrObject = array.getJSONObject(i); 42 System.out.println("unique_id is " 43 + arrObject.getString("unique_id")); 44 } 45 } 46 47 }
运行结果如下: