网站开发用php还是js/google推广seo
JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。
JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。
maven:
<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20140107</version>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version>
</dependency>
1.通过原生生成json数据格式。
JSONObject zhangsan = new JSONObject();try {//添加zhangsan.put("name", "张三");zhangsan.put("age", 18.4);zhangsan.put("birthday", "1900-20-03");zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});zhangsan.put("null", null);zhangsan.put("house", false);System.out.println(zhangsan.toString());} catch (JSONException e) {e.printStackTrace();}
2.通过hashMap数据结构生成
HashMap<String, Object> zhangsan = new HashMap<>();zhangsan.put("name", "张三");zhangsan.put("age", 18.4);zhangsan.put("birthday", "1900-20-03");zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});zhangsan.put("null", null);zhangsan.put("house", false);System.out.println(new JSONObject(zhangsan).toString());
3.通过实体生成
User zhangsan=new User();zhangsan.put("name", "张三");zhangsan.put("age", 18.4);zhangsan.put("birthday", "1900-20-03");zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});zhangsan.put("null", null);zhangsan.put("house", false);System.out.println(new JSONObject(zhangsan));
4.解析json数据
//读取json文件路径File file = new File(jsonTest.class.getResource("/zhangsan.json").getFile());try {//读取json内容String s = FileUtils.readFileToString(file);//转换json对象JSONObject jsonObject = new JSONObject(s);if(!jsonObject.isNull("name")){ //从文件读取JSON判断nullSystem.out.println(jsonObject.getString("name"));}System.out.println(jsonObject.getString("birthday"));System.out.println(jsonObject.getBoolean("house"));System.out.println(jsonObject.getDouble("age"));JSONArray majar = jsonObject.getJSONArray("majar"); //遍历数组for(int i=0,lengths=majar.length();i<lengths;i++){String o = (String)majar.get(i);System.out.println(i+1+":"+o);}} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();