一、fastjson2
FastJson对于json格式字符串的解析主要用到三个类
1.JSON:解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换
2.JSONObject:json对象
3.JSONArray: json数组对象
1.1、引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
1.2、使用
import java.math.BigDecimal;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
public class Book {
private Long id;
@JSONField(name = "name")
private String name ;
private BigDecimal price;
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
public static void main(String[]args) {
Book book = new Book();
book.setId(90L);
book.setName("Success of mindset");
book.setPrice(new BigDecimal(88.8));
// 序列化
System.out.println("---JSON.toJSONString: "+JSON.toJSONString(book));
System.out.println("---JSONArray.toJSONString: "+JSONArray.toJSONString(book));
byte[] bytes = JSONB.toBytes(book);
System.out.println();
System.out.println();
// 反序列化
String str ="{\"id\": 11,\"name\": \"fastjson2\",\"price\": \"88.8\"}";
System.out.println("---JSON.parseObject: "+(Book)JSON.parseObject(str,Book.class));
JSONObject jsonObject = JSON.parseObject(str);
System.out.println("---jsonObject: "+jsonObject);
System.out.println("------jsonObject.getIntValue:"+jsonObject.getIntValue("id"));
System.out.println("---JSONB.parseObject: "+JSONB.parseObject(bytes,Book.class));
System.out.println();
System.out.println();
// JSON解析为JSONObject
String text = "{\"id\": 11,\"name\": \"fastjson2\",\"price\": \"99.8\"}";
System.out.println("---JSON.parseObject: "+JSON.parseObject(text));
}
}
/*
---JSON.toJSONString: {"id":90,"name":"Success of mindset","price":88.7999999999999971578290569595992565155029296875}
---JSONArray.toJSONString: {"id":90,"name":"Success of mindset","price":88.7999999999999971578290569595992565155029296875}
---JSON.parseObject: Book{id=11, name='fastjson2', price=88.8}
---jsonObject: {"id":11,"name":"fastjson2","price":"88.8"}
------jsonObject.getIntValue:11
---JSONB.parseObject: Book{id=90, name='Success of mindset', price=88.7999999999999971578290569595992565155029296875}
---JSON.parseObject: {"id":11,"name":"fastjson2","price":"99.8"}
*/