使用java生成Json数据

来源:互联网 发布:淘宝交易规则 编辑:程序博客网 时间:2024/05/16 11:07
  1. import org.json.JSONArray;  
  2.   
  3. import org.json.JSONException;  
  4.   
  5. import org.json.JSONObject;  
  6.   
  7.    
  8.   
  9. public class TestJson {  
  10.   
  11.    public static void main(String[] args) {  
  12.   
  13.       JSONObject jsonObj = new JSONObject();//创建json格式的数据  
  14.   
  15.       JSONArray jsonArr = new JSONArray();//json格式的数组  
  16.   
  17.       JSONObject jsonObjArr = new JSONObject();  
  18.   
  19.       try {  
  20.   
  21.          jsonObjArr.put("item1""value1");  
  22.   
  23.          jsonObjArr.put("item2""value2");  
  24.   
  25.          jsonArr.put(jsonObjArr);//将json格式的数据放到json格式的数组里  
  26.   
  27.          jsonObj.put("rows", jsonArr);//再将这个json格式的的数组放到最终的json对象中。  
  28.   
  29.          System.out.println(jsonObj.toString());  
  30.   
  31.       } catch (JSONException e) {  
  32.   
  33.          // TODO Auto-generated catch block  
  34.   
  35.          e.printStackTrace();  
  36.   
  37.       }  
  38.   
  39.    }  
  40.   
  41. }  
  42.   
  43.    
  44.   
  45. 最终程序生成的数据格式就如下:  
  46.   
  47. {"rows":[{"item1":"value1","item2":"value2"}]}

  原文:http://blog.csdn.net/tarena_xhf/article/details/7405636


原创粉丝点击