JASN解析

Gson

       将对象转换为JSON字符串

       转换JSON字符串的步骤:

           1. 引入JAR包

           2. 在需要转换JSON字符串的位置编写如下代码即可:

          String json = new Gson().toJSON(要转换的对象);

案例:Book b = BookDao.find();

         String json = new Gson().toJson(b);

         System.out.println(json);

将JSN字符串转换为对象

        1. 引入JAR包

        2. 在需要转换Java对象的位置, 编写如下代码:

        对象 = new Gson().fromJson(JSON字符串,对象类型.class);

案例:String json = "{\"id\":1,\"name\":\"Ocean\",\"author\":\"呵呵呵 \",\"info\":\"live universe\",\"price\":19.98}";

           Book book = new Gson().fromJson(json, Book.class);   

           System.out.println(book);

package com;

import com.google.gson.Gson;

import java.util.Objects;

public class book {
    private String id;

    @Override
    public String toString() {
        return "book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }

    private String name;
    private String info;


    public book(String id, String name, String info) {
        this.id = id;
        this.name = name;
        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);
    }

    public book() {
    }

    public static void main(String[] args) {
//创建Gson对象
        Gson gson = new Gson();
//创建对象
        book b = new book("01","海洋","海洋奥秘");
        String s = gson.toJson(b);
//打印
        System.out.println(s);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值