JSON——Java中的使用

1. 构建JSON方法(数据——>JSON)

这里使用Maven构建项目

在pom.xml中添加如下依赖

 <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20090211</version>
    </dependency>

1.1 创建JSONObject对象,利用put(key,value)赋值,toString() 打印出JSON格式

关键词:JSONObject对象,put(), toString()

public class JsonObjectSimple {

    public static void main(String[] args) {
        jSONObjectSimple();
    }
    
    private static void jSONObjectSimple() {

        JSONObject xiaofeng=new JSONObject();
        Object nullObj=null;//因为put()方法的原因,这里不能直接使用null,所以创建null的对象来跳过编译器的检查
        try {
            xiaofeng.put("name", "小峰");
            xiaofeng.put("age", 22);
            xiaofeng.put("birthday", "1999-11-22");
            xiaofeng.put("school", "Qinghua University");
            xiaofeng.put("major", new String[] {"sing","coding"});
            xiaofeng.put("girlfriend", "true");
            xiaofeng.put("car",nullObj); //不能直接使用null,需要创建null的对象来跳过编译器的检查
            xiaofeng.put("comment","JSON里不能直接使用注释,需要添加时可通过此方式。。");
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
        System.out.println(xiaofeng.toString());     
    }   
}

控制台输出后复制其到 http://www.jsoneditoronline.org/ 可查看 JSON 数据结构

1.2 通过 HashMap 构建

 关键词:HashMap() , put() , toString() , JSONObject(xiaofeng)

private static void createJSONByMap() {

        Map<String,Object> xiaofeng=new HashMap<String,Object>();
        Object nullObj=null;
        xiaofeng.put("name", "小峰");
        xiaofeng.put("age", 22);
        xiaofeng.put("birthday", "1999-11-22");
        xiaofeng.put("school", "Qinghua University");
        xiaofeng.put("major", new String[] {"sing","coding"});
        xiaofeng.put("girlfriend", "true");
        xiaofeng.put("car",nullObj); //不能直接使用null,需要创建null的对象来跳过编译器的检查
        xiaofeng.put("comment","JSON里不能直接使用注释,需要添加时可通过此方式。。");

        System.out.println(new JSONObject(xiaofeng).toString());
    }

3. 使用 JavaBean 创建 JSON

关键词:JavaBean,  setXxx(),  JSONObject(xiaofeng)

 首先创建 JavaBean 类Person(略),  之后创建。。。

private static void createJSONByBean() {
      //创建Person对象,利用set()方法赋值,最后转为JSONObject对象输出
        Person xiaofeng=new Person();
        xiaofeng.setName("小峰");
        xiaofeng.setAge(22.5);
        xiaofeng.setGirlfriend(true);
        xiaofeng.setMajor(new String[]{"唱歌","coding"});
        
        System.out.println(new JSONObject(xiaofeng));            
    }

注意,在创建JavaBean时,由于JSON不支持date格式,所以日期格式需要设置为String类型,这也是JSON的缺陷。

2. 解析读取JSON数据(JSON——>数据)

xiaofeng.json
{
  "birthday": "1999-11-22",
  "girlfriend": "true",
  "major": [
    "sing",
    "coding"
  ],
  "school": "Qinghua University",
  "car": null,
  "name": "小峰",
  "comment": "JSON里不能直接使用注释,需要添加时可通过此方式。。",
  "age": 22
}

从文件中读取JSON

关键词:

ReadJSON.class.getResource("/xiaofeng.json").getFile() ,JSONArray,readFileToString(file)

public class ReadJSON {
    
    public static void main(String[] args) throws IOException, JSONException {
        //获取本文件路径下的json文件
        File file=new File(ReadJSON.class.getResource("/xiaofeng.json").getFile());
        //读取json文件内容
        String content=FileUtils.readFileToString(file);
        JSONObject jsonObject =new JSONObject(content);
System.out.println(
"姓名是 :"+jsonObject.getString("name")); System.out.println("年龄是 :"+jsonObject.getDouble("age")); System.out.println("有女朋友吗 ?"+jsonObject.getBoolean("girlfriend"));
//数组类型转换成JSONArray类型来解析,不能直接读取 JSONArray majorArray
=jsonObject.getJSONArray("major"); for(int i=0;i<majorArray.length();i++){ String m=(String) majorArray.get(i); System.out.println("专业——"+(i+1)+m); } } }

控制台输出

              

为增加程序健壮性,可在JSON数据解析时加入 非空【isNull()】 判断

     //判断 name 是否为空
        if (!jsonObject.isNull("name")) {
            System.out.println("姓名是 :" + jsonObject.getString("name"));
        }
        //反例,无输出
        if (!jsonObject.isNull("nme")) {
            System.out.println("姓名是 :" + jsonObject.getString("name"));
        }

        System.out.println("年龄是 :" + jsonObject.getDouble("age"));
原文地址:https://www.cnblogs.com/zjfjava/p/6842453.html