工具-JSON

简介

  • JSON
    JavaScript Object Notation JS对象简谱,是一种轻量级的数据交换格式。

对象格式

在这里插入图片描述

数组格式

在这里插入图片描述

案例

{
	"name":"何同学",
	"age":18,
	"pengyou":["张三","李四","王二","麻子",{
			"name":"野马老师",
			"info":"像匹野马一样狂奔在技术钻研的道路上"
		}],
	"heihei":{
		"name":"大长刀",
		"length":"40m"
	}
}

Gson 和 FastJson

  • 测试类BOOK
public class BOOK {
    private String id;
    private String name;
    private String info;

    public BOOK() {
    }

    public BOOK(String id, String name, String info) {
        this.id = id;
        this.name = name;
        this.info = info;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BOOK book = (BOOK) o;
        return Objects.equals(id, book.id) &&
                Objects.equals(name, book.name) &&
                Objects.equals(info, book.info);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, info);
    }

    @Override
    public String toString() {
        return "BOOK{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }
}
  • Gson(类转JSON)
//BOOK对象转JSON语言
BOOK book = new BOOK("100","一本书","我是一本书");
		//1.    创建Gson对象
        Gson g = new Gson();
        //2.    转换
        String s = g.toJson(book);
  • Gson(JSON 转类)
//{"id":"100","name":"一本书","info":"我是一本书"}转BOOK对象
		//1.    创建Gson对象
        Gson g = new Gson();
        //2.    转换
        BOOK book = g.fromJson("{\"id\":\"100\",\"name\":\"一本书\",\"info\":\"我是一本书\"}", BOOK.class);
  • FastJson(类转JSON)
BOOK book = new BOOK("111","我也是一本书","这也一本书");
        //1.    转换
        String s = JSON.toJSONString(book);
  • FastJson (JSON转类)
//{"id":"111","info":"这也一本书","name":"我也是一本书"}
		//1.    转对象
        BOOK book = JSON.parseObject("{\"id\":\"111\",\"info\":\"这也一本书\",\"name\":\"我也是一本书\"}", BOOK.class);
        //2.    转数组["一","二","三"]
        List<String> strings = JSON.parseArray("[\"一\",\"二\",\"三\"]", String.class);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值