Java json(com.google.gson)

JSON 官方文档

http://www.json.org/

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON(JavaScript对象标记法)是一个轻量级的数据交换格式。它便于人类读写。也便于机器分析和生成。它基于JavaScript编程语言的一个子集,标准ECMA-262 第三版 - 1999年12月。JSON是一种完全独立的文本格式语言,但是使用习惯类似C家族的语言,包括C, C++, C#, Java, JavaScript, Perl, Python, 和其它语言。这种特性使得JSON称为一个理想的数据交换语言。

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

JSON格式建立在以下两种结构上:

  • 一个名称/值对的集合。在多种语言中,它们被实现为对象,记录,结构,字典,哈希表,键列表, 关联数组。
  • 一个有序的值列表。在大多数语言中,它被实现为数组,向量,列表或序列。

这些都是通用的数据结构,几乎所有的现代编程语言都以一种或另一种形式支持它们。它使得编程语言可以基于那些结构的数据格式来交换数据成为可能。

在JSON中,数据采用如下的组成形式:

一个对象是一个无序的名称/值对的集合。一个对象由左花括号开始,右花括号结尾。每一个名字后面都跟着冒号,并且每一对名称/值对都用逗号分隔。

这里写图片描述

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

数组是一个有序的值集合。一个数组以左括弧起始,以右括弧终止。值使用逗号分割。

这里写图片描述

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

值可以是用双引号包起来的字符串,或者一个数字,或者真或假或空,或者一个对象或者一个数组。它们均可以嵌套使用。

这里写图片描述

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

字符串是零个或多个的Unicode字符序列,被双引号封装起来,使用反斜杠来转义。单个字符被表示为一个单一字符的字符串。字符串非常类似C或者Java的字符串。

这里写图片描述

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

数字非常类似C或者Java中的数字,除了不使用的八进制与十六进制格式。

这里写图片描述

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

空白符会被插入到任何令牌中间。除了少量编码细节,完全是描述语言。

这里写图片描述

google-gson 的GitHub地址

https://github.com/google/gson

配置方式在Maven中

http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.8.0%7C

这里写图片描述

jar包下载地址如下

http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/

这里写图片描述

JSON在线编辑器

http://www.bejson.com/jsoneditoronline/

这里写图片描述

代码实战

package com.demo.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.management.DescriptorKey;

import com.demo.test.JsonDemo.GsonAnnotationCls.Color;
import com.demo.test.JsonDemo.JsonCls.Link;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

public class JsonDemo {

    /** 标准的JSON字符串 */
    private static final String JSON_STR = "{"+
        "\"name\": \"BeJson\","+
        "\"url\": \"http://www.bejson.com\","+
        "\"page\": 88,"+
        "\"isNonProfit\": true,"+
        "\"address\": {"+
            "\"street\": \"科技园路\","+
            "\"city\": \"江苏苏州\","+
            "\"country\": \"中国\""+
        "},"+
        "\"links\": ["+
            "{"+
                "\"name\": \"Google\","+
                "\"url\": \"http://www.google.com\""+
            "},"+
            "{"+
                "\"name\": \"Baidu\","+
                "\"url\": \"http://www.baidu.com\""+
            "},"+
            "{"+
                "\"name\": \"SoSo\","+
                "\"url\": \"http://www.SoSo.com\""+
            "}"+
        "]"+
    "}";

    /** 无头JSON数组字符串 */
    private static final String NO_HEADER_JSON_ARRAY_STR = "["+
        "{"+
            "\"name\": \"Google\","+
            "\"url\": \"http://www.google.com\""+
        "},"+
        "{"+
            "\"name\": \"Baidu\","+
            "\"url\": \"http://www.baidu.com\""+
        "},"+
        "{"+
            "\"name\": \"SoSo\","+
            "\"url\": \"http://www.SoSo.com\""+
        "}"+
    "]";

    private static final String ARRAY_HEADER_NAME = "links";

    /** 有头JSON数组字符串(实际上是JSON对象) */
    private static final String JSON_ARRAY_STR = "{" + 
        "\"" + ARRAY_HEADER_NAME + "\":" +
        NO_HEADER_JSON_ARRAY_STR + 
    "}";

    static class JsonCls {
        private String name;
        private String url;
        private int page;
        private boolean isNonProfit;
        private HashMap<String, String> address;
        private Link[] links;

        @Override
        public String toString() {
            return "Test [name=" + name + ", url=" + url + ", page=" + page + ", isNonProfit=" + isNonProfit + ", address=" + address + ", links=" + Arrays.toString(links) + "]";
        }

        static class Link {
            private String name;
            private String url;

            @Override
            public String toString() {
                return "Link [name=" + name + ", url=" + url + "]";
            }
        }
    }

    /**
     * @Expose 可以区分实体中不想被序列化的属性
     * <ol>
     * <li>(serialize=boolean) 序列化 默认 true
     * <li>(deserialize=boolean) 反序列化 默认 true
     * </ol>
     * 
     * @SerializedName 标签定义属性序列化后的名字
     */
    static class GsonAnnotationCls {
        @Expose
        @SerializedName("clothName")
        private String name;
        //transient 短暂的,该字段在序列化和反序列化时会被忽略
        private transient String brand;
        //奇怪的是@Expose不起作用了
        @Expose(serialize=false,deserialize=false)
        private int size;
        //java中的枚举类型会被当成字符串来存储
        @Expose
        private Color color;

        public GsonAnnotationCls(String name, String brand, int size, Color color) {
            this.name = name; 
            this.brand = brand;
            this.size = size;
            this.color = color;
        }

        @Override
        public String toString() {
            return "GsonAnnotationCls [name=" + name + ", brand=" + brand + ", size=" + size + ", color=" + color + "]";
        }

        enum Color {  
            Red,
            Green,
            Blue,
        } 
    }

    public static void main(String[] args) {
        Gson gson = new Gson();

        //标准JSON字符串 -> 对象
        JsonCls test = gson.fromJson(JSON_STR, JsonCls.class);
        String testStr = test.toString();
        System.out.println(testStr);

        //对象 -> 标准JSON字符串
        testStr = gson.toJson(test);
        System.out.println(testStr);

        //无头JSON数组字符串 -> 数组
        //GSON 提供了 TypeToken 这个类来帮助我们捕获(capture)像 List 这样的泛型信息。Java编译器会把捕获到的泛型信息编译到这个匿名内部类里,然后在运行时就可以被 getType() 方法用反射的 API 提取到。
        Link[] linkArr = gson.fromJson(NO_HEADER_JSON_ARRAY_STR, new TypeToken<Link[]>() {}.getType());
        System.out.println(Arrays.toString(linkArr));

        //无头JSON数组字符串 -> 列表
        List<Link> links = gson.fromJson(NO_HEADER_JSON_ARRAY_STR, new TypeToken<List<Link>>() {}.getType());
        System.out.println(links.toString());

        /*
         * 有头JSON数组字符串(实际上是JSON对象) -> 列表
         * Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
         */
        // links = gson.fromJson(JSON_ARRAY_STR, new TypeToken<List<Link>>() {}.getType());
        // System.out.println(links.toString());

        // 有头JSON数组字符串(实际上是JSON对象) -> JsonObject -> JsonArray -> 数组
        JsonParser jsonParser =  new JsonParser();
        JsonElement jsonElement = jsonParser.parse(JSON_ARRAY_STR);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonArray jsonArray = jsonObject.getAsJsonArray(ARRAY_HEADER_NAME);
        linkArr = gson.fromJson(jsonArray, new TypeToken<Link[]>() {}.getType());
        System.out.println(Arrays.toString(linkArr));

        //包含枚举和注解的对象转换为json字符串
        GsonAnnotationCls gsonAnnotationCls = new GsonAnnotationCls("unknown", "优衣库", 24, Color.Blue);
        testStr = gson.toJson(gsonAnnotationCls);
        System.out.println(testStr);
        gsonAnnotationCls = gson.fromJson(testStr, GsonAnnotationCls.class);
        System.out.println(gsonAnnotationCls);
    }
}

运行输出

这里写图片描述

Test [name=BeJson, url=http://www.bejson.com, page=88, isNonProfit=true, address={country=中国, city=江苏苏州, street=科技园路}, links=[Link [name=Google, url=http://www.google.com], Link [name=Baidu, url=http://www.baidu.com], Link [name=SoSo, url=http://www.SoSo.com]]]
{"name":"BeJson","url":"http://www.bejson.com","page":88,"isNonProfit":true,"address":{"country":"中国","city":"江苏苏州","street":"科技园路"},"links":[{"name":"Google","url":"http://www.google.com"},{"name":"Baidu","url":"http://www.baidu.com"},{"name":"SoSo","url":"http://www.SoSo.com"}]}
[Link [name=Google, url=http://www.google.com], Link [name=Baidu, url=http://www.baidu.com], Link [name=SoSo, url=http://www.SoSo.com]]
[Link [name=Google, url=http://www.google.com], Link [name=Baidu, url=http://www.baidu.com], Link [name=SoSo, url=http://www.SoSo.com]]
[Link [name=Google, url=http://www.google.com], Link [name=Baidu, url=http://www.baidu.com], Link [name=SoSo, url=http://www.SoSo.com]]
{"clothName":"unknown","size":24,"color":"Blue"}
GsonAnnotationCls [name=unknown, brand=null, size=24, color=Blue]
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值