Json 基础详解

1.什么是Json,有什么优点
          Json (JavaScript Object Notation),是一种与开发语言无关的、轻量级的数据格式,更确切的是,它是一种数据格式或规范,对人来说具有易读、易编写的性质,对于机器来说易于程序解析与生成。
例:
{
 “name”:“Terence,
“age”:25,
“birthday”:“1993-11-09”,
“school”:”qushi”,
“major”:[“计算机”,“挖掘机”],
“has_girlFriend”:false,
“car”:null,
“house”:null,
“comments”:”这是一个注释”
}
2.数据表示
    数据结构:Object,Array
    基本类型:string,number,true,false,null
    Object:使用{}包含键值对结构,key必须是string类型,value值为其他任何基本类型或者数据结构。
    Array:数组使用中括号[]来表示,使用逗号来分割元素。

3.JSON简单使用
    在官方网站(http://www.json.org.cn/)上有各种语言的Json包,通过这些包,可以对Json做相应的处理。最常用的就是org.json。
(1) 引入依赖
<Dependencies>
    <Dependency>
      <GroupId> org.json </ groupId>
      <ArtifactId> json </ artifactId>
      <version> 20090211 </ version>
    </ Dependency>
    <Dependency>
      <GroupId> commons-io </ groupId>
      <ArtifactId> commons-io </ artifactId>
      <version> 2.4 </ version>
    </ Dependency>
 </ Dependencies>
(2) 以不同的方式实施的Json
     ① 使用的JSONObject实现的Json
     ② 使用map实现的Json
     ③  使用Bean 实现的Json
package com.guigu.json;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonObjectSample {
    public static void main(String[] args) {
        newJSONObject();
        createJsonByMap();
        createJsonByBean();
    }
    // 1.使用JsonObject实现Json
    private static void newJSONObject() {
        JSONObject terence = new JSONObject();
        Object nullObj = null;
        try {
            terence.put("name", "simeng");
            terence.put("age", 25);
            terence.put("birthday", "1992-11-09");
            terence.put("school", "qushi");
            terence.put("major", new String[] { "程序员", "教师" });
            terence.put("has_girlfriend", false);
            terence.put("car", nullObj);
            terence.put("house", nullObj);
            terence.put("comment", "注释");
            System.out.println(terence.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    // 2.使用Map实现Json
    private static void createJsonByMap() {
        Map<String, Object> terence = new HashMap<String, Object>();
        Object nullObj = null;
        terence.put("name", "simeng");
        terence.put("age", 25);
        terence.put("birthday", "1992-11-09");
        terence.put("school", "qushi");
        terence.put("major", new String[] { "程序员", "教师" });
        terence.put("has_girlfriend", false);
        terence.put("car", nullObj);
        terence.put("house", nullObj);
        terence.put("comment", "注释");
    }
    // 3.使用Bean实现Json
    private static void createJsonByBean() {
        DaShen terence = new DaShen();
        terence.setName("simeng");
        terence.setAge(25);
        terence.setBirthday("1990-5-9");
        terence.setSchool("qushi");
        terence.setMajor(new String[] { "程序员", "教师" });
        terence.setHas_girlfriend(false);
        terence.setComment("注释");
        terence.setCar(null);
        terence.setHouse(null);
        System.out.println(new JSONObject(terence));
    }
}
DaShen.java
Public class DaShen {
   @SerializedName("NAME") 
   private String name;
   private String school;
   private boolean has_girlfriend;
   private double age;
   private Object car;
   private Object house;
   private String[] major;
   private String comment;
   private String birthday;
     Get, set, toString ...
}
     ④Json解析
Package com.guigu.json;
Import java.io.File;
Import org.apache.commons.io.FileUtils;
import org.json.JSONObject;

public class ReadJsonSample {
     // 反向解析为一个json
     public static void main(String[] args) throws Exception {
          File file = new File(ReadJsonSample.class.getResource("/terence.json").getFile());
          String content = FileUtils.readFileToString(file);
          JSONObject jsonObject = new JSONObject(content);
          if (!jsonObject.isNull("name")) {
              System.out.println("姓名:" + jsonObject.getString("name"));
          }
          System.out.println("年龄:" + jsonObject.getDouble("age"));
     }
}
4.GSON解析JSON
(1) 为什么使用Gson
     Gson是google一个比较流行的开源项目,相比于json,Gson的功能更加全面,性能更加强大,使用方式也更加便捷简单,一般使用Gson生成json。
     使用引入依赖
<dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.4</version>
</dependency>
(2) Gson读取
     相比于用JSONObject实现Json,借助Gson具有更多的优势,更加便捷,如下常用的几方面:
①注解序列化属性
     给bean中类的某个属性加上注解,序列化某个属性,可以加上别名,更加安全,不易出错。
public class DaShen {
   @SerializedName("NAME")
   private String name;
   private String school;
   private boolean has_girlfriend;
   private double age;
   private Object car;
   private Object house;
   private String[] major;
   private String comment;
   private String birthday;
}
     如上所示,给属性name加上注解,则返回的是NAME.
package com.guigu.json;
import com.google.gson.Gson;
public class GsonCreateSample {
     public static void main(String[] args) {
          DaShen terence = new DaShen();
          terence.setName("simeng");
          terence.setAge(25);
          terence.setBirthday("1990-5-9");
          terence.setSchool("qushi");
          terence.setMajor(new String[] { "程序员", "教师" });
          terence.setHas_girlfriend(false);
          terence.setComment("注释");
          terence.setCar(null);
          terence.setHouse(null);
          Gson gson = new Gson();
          System.out.println(gson.toJson(terence));
     }
}
②利用Gson格式化Json
     可以利用Gson的GsonBuilder类设置规范化的格式(setPrettyPrinting),然后利用该类的create()方法创建gson,从而转化为json,这样呈现出来的json数据直接就是规范化的格式,看着更好。
package com.guigu.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonCreateSample {
     public static void main(String[] args) {
          DaShen terence = new DaShen();
          terence.setName("simeng");
          terence.setAge(25);
          terence.setBirthday("1990-5-9");
          terence.setSchool("qushi");
          terence.setMajor(new String[] { "程序员", "教师" });
          terence.setHas_girlfriend(false);
          terence.setComment("注释");
          terence.setCar(null);
          terence.setHouse(null);

          //Gson gson = new Gson();
          //System.out.println(gson.toJson(terence));

          GsonBuilder gsonBuilder=new GsonBuilder();
          gsonBuilder.setPrettyPrinting();//设置出漂亮的格式
          Gson gson2=gsonBuilder.create();
          System.out.println(gson2.toJson(terence));
     }
}
③ 利用GSON生成新的策略
     可以利用Gson生成新的策略,通过带入回调函数添加额外功能,生成个性化的json,很显然,JSONObject不具备这样的功能。
     GsonBuilder gsonBuilder=new GsonBuilder();
     gsonBuilder.setPrettyPrinting();       
     //利用Gson生成一个新的策略,生成个性化的json
     //传给这个策略一个回调函数,通过回调函数添加一些额外的功能
     //如下所示的策略,给age属性一个新的别名AGE
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() 
      { 
          public String translateName(Field f) 
          { 
              if(f.getName().equals("age")) 
                  return"AGE"; 
              else 
                  return f.getName(); 
          } 
      }); 
Gson gson3=gsonBuilder.create(); 
System.out.println(gson3.toJson(terence)); 
④ 隐藏/排除属性
     在bean中,用关键字transient修饰的属性用Gson转换成Json后可隐藏改属性。
public class DaShen { 
   private Objectcar; 
   private Objecthouse; 
   private String[]major; 
   private Stringcomment; 
   private Stringbirthday; 
   public transient String ignore; 
} 
      该类中的属性ignore在json中不可显示。
(3) Gson解析
        使用Gson可以实现双向生成,不仅可以用Bean生成Json,还可以用Json生成Bean.
DaShenGson.java
public class DaShenGson {
     private String name;
     private String school;
     private boolean has_girlfriend;
     private double age;
     private Object car;
     private Object house;
     private List<String> major;
     private String comment;
     private Date birthday;
}
① 利用GSON逆向解析生成Bean
     直接利用GSON的fromJson() 方法将其转化为bean;
public class GsonReadSample {
     public static void main(String[] args) throws Exception {
          File file = new File(ReadJsonSample.class.getResource("/terence.json").getFile());
          String content = FileUtils.readFileToString(file);
          Gson gson = new Gson();
          DaShen terence = gson.fromJson(content, DaShen.class);
          System.out.println(terence.toString());
     }
}
②设置日期格式
File file = new File(ReadJsonSample.class.getResource("/terence.json").getFile());
String content = FileUtils.readFileToString(file);
Gson g=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();       
DaShen terence = g.fromJson(content,DaShen.class);
System.out.println(terence.getBirthday());
③ 不管是List还是Set,都会自动转化,不需要做额外的辅助,直接输出就可以看到了
File file = new File(ReadJsonSample.class.getResource("/terence.json").getFile());
String content = FileUtils.readFileToString(file);
Gson g=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DaShenGson terence = g.fromJson(content,DaShenGson.class);
System.out.println(terence.getClass());
System.out.println(terence.getMajor());
System.out.println(terence.getMajor().getClass());
     PS:如想通过代码更好的理解Json,请:https://github.com/luomingkui/json
     PS:更多JSON相关的知识,请参考:http://www.json.cn/wiki.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员学习圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值