1.首先创建一个简单Maven项目。 2.本次使用jar包:
<!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>3.org-json的使用 (1).创建一个JSON对象,并向里面插入数据
public static void jsonObject() { JSONObject wangxiaoer = new JSONObject(); Object nullObject = null; try { wangxiaoer.put("name", "王小二"); wangxiaoer.put("age", 10); wangxiaoer.put("birthday", "1996/09/13"); wangxiaoer.put("school", "南翔"); wangxiaoer.put("major", new String[]{"炒菜","挖掘机"}); wangxiaoer.put("has_girlfriend", false); wangxiaoer.put("car", nullObject); wangxiaoer.put("comment", "这是一个注释"); System.out.println(wangxiaoer.toString()); } catch (JSONException e) { e.printStackTrace(); } } (2).通过JavaBean来创建JSON对象 public static void createJsonByBean() { Person person = new Person(); person.setName("王i下奥尔"); person.setAge(10); person.setBirthday("1996/09/13"); person.setHas_girlfirend(false); person.setMajor(new String[]{"af","as"}); person.setCar(null); person.setSchool("南翔"); person.setComment("这是一个注释"); System.out.println(new JeNObject(person));(3).通过Map集合来创建JSON对象
public static void createJsonByMap() { Map<String, Object> wangxiaoer = new HashMap<>(); Object nullObject = null; wangxiaoer.put("name", "王小二"); wangxiaoer.put("age", 10); wangxiaoer.put("birthday", "1996/09/13"); wangxiaoer.put("school", "南翔"); wangxiaoer.put("major", new String[]{"炒菜","挖掘机"}); wangxiaoer.put("has_girlfriend", false); wangxiaoer.put("car", nullObject); wangxiaoer.put("comment", "这是一个注释"); System.out.println(wangxiaoer.toString()); JSONObject jsonObject = new JSONObject(wangxiaoer); System.out.println(jsonObect.toString()); } (4).对JSON文件的解析 File file = new File(ReadJsonSimple.class.getResource("wagnxiaoer.json").getFile()); String content = FileUtils.readFileToString(file); JSONObject jsonObject = new JSONObject(content); System.out.println(jsonObject.get("name")); JSONArray array = jsonObject.getJSONArray("major"); if (!jsonObject.isNull("car")) { System.out.println(jsonObject.get("car")); }注意事项:org.json存在jar包版本兼容问题,如果用2009版本的jar包会存在一个无法解析数组类型数据的问题。而且JSONObject对象无法将JSON对象转换成JAVA中的对象。
