java组装json和提取一个json的例子

package jsonparsed;
import net.sf.json.JSONException;   
import net.sf.json.JSONObject; 
import net.sf.json.JSONArray;
public class jsonparsed {
    // 创建JSONObject对象
    private static JSONObject createJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ret", new Integer(0));
        jsonObject.put("msg", "query");
        JSONObject dataelem1=new JSONObject();
        //{"deviceid":"SH01H20130002","latitude":"32.140","longitude":"118.640","speed":"","orientation":""}
        dataelem1.put("deviceid", "SH01H20130002");
        dataelem1.put("latitude", "32.140");
        dataelem1.put("longitude", "118.640");
 
        JSONObject dataelem2=new JSONObject();
        //{"deviceid":"SH01H20130002","latitude":"32.140","longitude":"118.640","speed":"","orientation":""}
        dataelem2.put("deviceid", "SH01H20130002");
        dataelem2.put("latitude", "32.140");
        dataelem2.put("longitude", "118.640");
        
     // 返回一个JSONArray对象
        JSONArray jsonArray = new JSONArray();
        
        jsonArray.add(0, dataelem1);
        jsonArray.add(1, dataelem2);
        jsonObject.element("data", jsonArray);

        
        return jsonObject;
    }
public static void main(String [] args){
    JSONObject jsonObject = jsonparsed.createJSONObject();//静待  方法,直接通过类名+方法调用
    // 输出jsonobject对象
    System.out.println("jsonObject:" + jsonObject);
    // 添加JSONArray后的值


    // 根据key返回一个字符串
    String username = jsonObject.getString("ret");
    System.out.println("username==>" + username);    
}
}

 

posted @ 2016-01-16 13:20  星辰之力  阅读(4344)  评论(0编辑  收藏  举报