初学JSON

什么是JSON

JSON是一种与开发语言无关,轻量级的数据格式。全称 JavaScript Object Notation.

数据结构

Object
Array

基本类型

String , number , true , false , null

数据结构-Object
  • 使用花括号 {} 包含的键值对结构,Key 必须是string 类型,value 为任何基本类型或数据结构
数据结构-Array
  • 使用中括号 [] 来起始,并用逗号 ,分割元素
步骤
  1. 在 GitHub 上下载 json的包 JSON-java-master 并将其导入IDEA包中即可
  2. 开始进行代码操作:
  • 使用 JSONObject()
private static void JSONObject(){
        JSONObject xiaoxiao = new JSONObject();
        Object nullO = null;
        try {
            xiaoxiao.put("name", "xiaoxiao");
            xiaoxiao.put("age", 19.2);
            xiaoxiao.put("birthday", "2000-01-01");
            xiaoxiao.put("school", "北大");
            xiaoxiao.put("major", new String[]{"搓澡", "挖掘机"});  //注意vlaue取数组的表达
            xiaoxiao.put("has_girlfriend", false);
            xiaoxiao.put("car", nullO);
            xiaoxiao.put("house", nullO);
            xiaoxiao.put("comment", "这是一个注释");

            System.out.println(xiaoxiao.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
  • 使用 JsonByMap()
private static void createJsonByMap(){
        Map<String,Object> xiaoxiao = new HashMap<String,Object>();
        Object nullO = null;
        try {
            xiaoxiao.put("name", "xiaoxiao");
            xiaoxiao.put("age", 19.2);
            xiaoxiao.put("birthday", "2000-01-01");
            xiaoxiao.put("school", "北大");
            xiaoxiao.put("major", new String[]{"搓澡", "挖掘机"});   
            xiaoxiao.put("has_girlfriend", false);
            xiaoxiao.put("car", nullO);
            xiaoxiao.put("house", nullO);
            xiaoxiao.put("comment", "这是一个注释");

            System.out.println(new JSONObject(xiaoxiao).toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
  • 使用 createJsonByBean()
    通过 new 一个bean对象,向此对象中添加各属性信息,然后
    System.out.println(new JSONObject(xiaoxiao)); 输出即可

  • 从文件中读取 json 信息

public class ReadJSONSample {
    public static void main(String[] args) throws IOException {
        File f = new File("O:\\ JSON16\\src\\oym\\json\\xiaoxiao.json");
        //需要导入 commons-io jar包
        String content = FileUtils.readFileToString(f);  
        JSONObject jsonObject = new JSONObject(content);
        /判断该文件是否有此key值的方法
        if(!jsonObject.isNull("name")) {              
            System.out.println("姓名是:" + jsonObject.getString("name"));
        }
        if(!jsonObject.isNull("nickname")) {
            System.out.println("姓名是:" + jsonObject.getString("nickname"));
        }
        System.out.println("年龄是:" + jsonObject.getDouble("age"));
        System.out.println("有没有女人:" + jsonObject.getBoolean("has_girlfriend"));
        //如果 value 值为数组,用 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);
        }
    }
}
使用 gson (更简洁,更方便)
  • 下载 : com.google.code.gson
  • 导入:gson-2.8.5.jar
  • toJson 方法的使用
    Gson gson = new Gson();
    System.out.println(gson.toJson(xiaoxiao));  // xiaoxiao 为 javaBean 创建的对象
  • GsonBuilder 的使用
 GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();   //设置换行格式
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
            @Override
            public String translateName(Field field) {     //设置转译后属性名个改变
                if(field.getName().equals("school")){
                    return "SCHOOL";
                }
                return field.getName();
            }
        });
        Gson gson = gsonBuilder.create();    //用gsonBuilder来创建对象
        System.out.println(gson.toJson(xiaoxiao));
  • Gson解析 (fromJson的使用)
public static void main(String[] args) throws IOException {
		//接下来两行跟之前解析一样,解析同一个文件
        File f = new File("O:\\ JSON16\\src\\oym\\json\\xiaoxiao.json");
        String content = FileUtils.readFileToString(f);
        //创建 gson
        Gson gson = new Gson();
        Diaosi xiaoxiao = gson.fromJson(content,Diaosi.class);   
        System.out.println(xiaoxiao);
    }
  • Gson 需要解析Date()类型时办法:
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();  //Gson设置日期格式办法
        DiaosiWithBirthday xiaoxiao = gson.fromJson(content,DiaosiWithBirthday.class);
        System.out.println(xiaoxiao.getBirthday().toString());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值