首页 > 编程语言 > 详细

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

时间:2016-01-16 14:19:06      阅读:325      评论:0      收藏:0      [点我收藏+]
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);    
}
}

 

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

原文:http://www.cnblogs.com/zhujiabin/p/5135351.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!