Json及Json工具類

Json視頻javascript

什麼是Json

json是一種與開發語言無關的,輕量級的數據格式,全稱:javascript object notationjava

Json基礎

JSON 語法規則

JSON 語法是 JavaScript 對象表示語法的子集。json

  • 數據由逗號分隔
  • 大括號保存對象
  • 中括號保存數組

數據結構:對象、數組數組

基本類型:string,number,true,false,null數據結構

  • Object
{key:value,key:value...}

key:string類型

value:任何基本類型或Json可以使用的數據結構
  • Array
[value,value...]

value:任何基本類型或數據結構。

演示工具

{
  "name":"王小二",
  "age":22.3,
  "birthday":"1993-12-1",
  "school":"藍翔",
  "major":["理髮","挖掘機"],
  "has_girlfriend":false,
  "car":null,
  "house":null,
  "comment":"這是一個註釋"
}

JSON裏沒有註釋,可以使用comment來傳輸註釋的內容

Json In Java

org.json

在.pom中添加依賴ui

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

就能夠使用JsonObject工具了(下面是生成JsonObject對象的小例子)google

構建JsonObject對象

Json數據

{
        "name":"王小二",
            "age":22.3,
            "birthday":"1993-12-1",
            "major":["語文","數學"],
            "car":null,
            "married":false,
            "comment":"這是一個註釋"
    }

 Java經過屬性一個個放入JsonObject中

public void jsonTest() {
        JSONObject jsonObject = new JSONObject();
        Object nullObj = null;
        jsonObject.put("name", "王小二");
        jsonObject.put("age", 22.3);
        jsonObject.put("date", "1993-12-1");
        jsonObject.put("majot", new String[]{"語文", "數學"});
        jsonObject.put("car", nullObj);
        jsonObject.put("married", false);
        jsonObject.put("comment", "這裏是註釋");

        System.out.println(jsonObject.toString());
    }

這裏是將上面的Json數據存在了JsonObject對象中了(若是put重複Key,將會覆蓋以前的數據)spa

使用HashMap構建JsonObject

public void jsonByMapTest() {


        HashMap map = new HashMap();
        Object nullObj = null;
        //往map中添加數據
        map.put("name", "王小二");
        map.put("age", 22.3);
        map.put("date", "1993-12-1");
        map.put("major", new String[]{"語文", "數學"});
        map.put("car", nullObj);
        map.put("married", false);
        map.put("comment", "這裏是註釋");

        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject.toString());
    }

使用JavaBean構建JsonObject

public class User{
   private String name;
   private double age;
   private String date;
   private String[] major;
   private Object car;
   private boolean married;
   private String content;
}
public void createJsonByBean()
    {
        User user=User();
        user.setName("王小二");
        user.setAge(25.9);
        user.setDate("1990-5-9");
        user.setMajor(new String[]{"Computer","qiqiqiqi"});
        user.setComment("sha,sha,sha,sha……");
        user.setCar(null);
        user.setMarried(false);

        System.out.println(new JSONObject(user));
   
    }

解析Json

pom文件中添加 common.io 方便文件的讀取code

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
public void test1() throws IOException {

        File file = new File("filepath");
        String jsonStr = FileUtils.readFileToString(file);
        JSONObject jsonObject = new JSONObject(jsonStr);

        System.out.println(jsonObject.get("name"));
        System.out.println(jsonObject.getDouble("age"));
        System.out.println(jsonObject.getBoolean("married"));
        JSONArray jsonArray = jsonObject.getJSONArray("major");
        for (int i = 0; i < jsonArray.length(); i++) {
            System.out.println((String) jsonArray.get(i));
        }

        System.out.println(jsonObject.toString());
    }

有些時候咱們讀取的文件可能跟咱們預期的內容不相符,那麼咱們就須要增長健壯性

咱們就要對轉化的JsonObject對象進行判斷

if (jsonObject.isNull("name")) {
            System.out.println(jsonObject.get("name"));
        }

JSON對象生成的方法;

  1. JsonObject jsonObject= new JsonObject (); // 第一種原生的
  2. JsonObject jsonObject= new JsonObject (hashMap);  //第二種
  3. JsonObject jsonObject= new JsonObject (obj);  //第三種 java bean

Gson

在pom文件中添加依賴

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

根據對象生成json對象

public void createJsonByBean()
    {
        User user=User();
        user.setName("王小二");
        user.setAge(25.9);
        user.setDate("1990-5-9");
        user.setMajor(new String[]{"Computer","qiqiqiqi"});
        user.setComment("sha,sha,sha,sha……");
        user.setCar(null);
        user.setMarried(false);

        Gson gson=new Gson();
        System.out.println(gson.toJson(user););
   
    }

修改的json中key的名稱

能夠對Pojo進行處理

@SerializedName("Name")
   private String name;

{「Name」:"王小二",*******}

若是在生成Json忽略掉某一屬性:(transient)

private transient String content;
//gson.toJson(user);獲取的json對象是格式化以後的(用的表較少)
 Gson gson = new GsonBuilder().create();

 解析Json對象(直接將json轉化爲Object對象)

public void readFileToString(User user) throws IOException {
        File file = new File("filepath");
        String str = FileUtils.readFileToString(file);

        Gson gson = new GsonBuilder().create();

        user = gson.fromJson(str, User.class);
        System.out.println(user.toString());
    }

Json中包含日期

前面例子咱們日期類型是以字符串的形式傳輸的

//private String date;
   private Date date;
public void readFileToString(User user) throws IOException {
        File file = new File("filepath");
        String str = FileUtils.readFileToString(file);

        Gson gson = new GsonBuilder().setDateForamt(""yyyy-MM-dd).create();
        //此時咱們獲取的user對象中的date爲Date類型
        user = gson.fromJson(str, User.class);
        System.out.println(user.toString());
    }

Json中包含集合類

//private String[] major;
 private List<String> major;
public void readFileToString(User user) throws IOException {
        File file = new File("filepath");
        String str = FileUtils.readFileToString(file);

        Gson gson = new GsonBuilder().setDateForamt(""yyyy-MM-dd).create();
        //此時咱們獲取的user對象中的major爲ArrayList類型
        user = gson.fromJson(str, User.class);
        System.out.println(user.getMajor().getClass());
    }

Gson相對於org.json的優勢:

  1. 支持日期
  2. 能夠轉換爲對象
  3. 集合操做

FastJson

將JavaBean轉化爲Json

User user = new User("王小二",22.3,"1993-12-1",new String[]{"語文","數學"},null,false, "這裏是註釋");
        System.out.println(JSON.toJSONString(user));

將集合類轉化爲Json

User user = new User("王小二",22.3,"1993-12-1",new String[]{"語文","數學"},null,false, "這裏是註釋");
        List<User> UserList = new ArrayList<User>();
        for(int i=0;i<5;i++) {
            UserList.add(user);
        }
        System.out.println(JSON.toJSONString(user));

格式化輸出Json

//格式化的輸出json內容
System.out.println(JSON.toJSONString(user,true););

解析Json爲Javabean

JSON.parseObject(jsonStr,User.class)

 解析Json爲集合類對象

List<User> UserList = new ArrayList<User>();
        for (int i = 0; i < 5; i++) {
            UserList.add(user);
        }
        // 過濾哪些屬性須要轉換
        // SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Student.class, "id","age");
        // String jsonStu =JSON.toJSONString(students,filter);

        String jsonUsers = JSON.toJSONString(UserList);
        System.out.println(jsonUsers);
        List<User> stu = JSON.parseObject(jsonUsers, new TypeReference<List<User>>() {
        });
        for (int i = 0; i < stu.size(); i++) {
            System.out.println(stu.get(i).toString());
        }

JskcJson

相關文章
相關標籤/搜索