Java与JSON

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

JSON格式

{
	"name":"张三".
	"age":18,
	"friends":["李四","王二",{
				"name":"麻子",
				"age":"20"
			}]
}

JSON解析的两种方式

1. Gson
  • 将对象转换为JSON字符串:

    String json = new Gson().toJson(对象名);
    
  • 将JSON字符串转换为对象:

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

    注意:数组[…]会转为ArrayList集合

e.g.

public static void main(String[] args){
    // 1. 创建Gson对象
    Gson g = new Gson();
    // 2. 转换
    Book b = new Book("100", "金苹果", "种植苹果真辛苦");
    String s = g.toJson(b);
}
public static void main(String[] args){
    // 1. 创建Gson对象
    Gson g = new Gson();
    // 2. 转换
    String s = "{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}";
    Book b = g.fromJson(s, Book.class); // 1
    HashMap data = g.fromJson(s, HashMap.class); // 2
}
2. Fastjson
  • 将对象转换为JSON字符串:

    String json = JSON.toJSONString(对象名);
    
  • 将JSON字符串转换为对象:

    类名 对象名 = JSON.parseObject(JSON字符串, 类名.class);
    
  • 将JSON字符串转换为ArrayList:

    List<类名> list = JSON.parseArray(JSON字符串, 类名.class);
    

e.g.

public static void main(String[] args){
    // 1. 转换
    Book b = new Book("100", "金苹果", "种植苹果真辛苦");
    String s = JSON.toJSONString(book);
}
public static void main(String[] args){
    // Object
    String s = "{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}";
    Book b = JSON.parseObject(s, Book.class);
    // ArrayList
    String s1 = "[\"一二三\",\"四五六\",\"七八九\"]";
    List<String> strings = JSON.parseArray(s1, String.class);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值