//导入json-org.jar包
import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; public class JsonWrite { public static void main(String[] args) throws JSONException { JsonWrite.JsonObj(); JsonWrite.JsonByMap(); JsonWrite.JsonByjavaBean(); } // 方法一,使用JSONObject public static void JsonObj() throws JSONException { JSONObject o1 = new JSONObject(); o1.put("id", 1); o1.put("name", "java"); JSONObject o2 = new JSONObject(); o2.put("id", 2); o2.put("name", "c++"); JSONObject obj = new JSONObject(); Object o = null; obj.put("name", "小明"); obj.put("age", 20); obj.put("car", false); obj.put("girlF", o); obj.put("hobby", new String[] { "上网", "看电影" }); obj.put("zy", new JSONObject[] { o1, o2 }); System.out.println(obj); } // 方法二,使用Map集合 public static void JsonByMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "小明"); map.put("age", 20); map.put("car", false); map.put("hobby", new String[] { "上网", "看电影" }); JSONObject obj = new JSONObject(map); System.out.println(obj); } // 方法三,使用JavaBean public static void JsonByjavaBean() { Person p = new Person(); p.setName("小明"); p.setAge(20); p.setCar(false); p.setHobby(new String[] { "上网", "看电影" }); JSONObject obj = new JSONObject(p); System.out.println(obj); } }
使用方法三需要写一个person类 public class Person { private String name; private int age; private boolean car; private String[] hobby; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isCar() { return car; } public void setCar(boolean car) { this.car = car; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } }
JSON方法写入
最新推荐文章于 2024-01-24 20:00:00 发布