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

时间:2023-03-08 17:27:19
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());
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(, dataelem1);
jsonArray.add(, 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);
}
}