Convert between json and object
1. Introduce pom
Here introduce Ali's jar package
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2. Convert the code
Book entity:
package com.email.demo.bean;
import lombok.Data;
@Data
public class Book {
private Integer id;
private Double price;
private String description;
private Float weight;
}
Main program method:
package com.email.demo.controller;
import com.alibaba.fastjson.JSON;
import com.email.demo.bean.Book;
public class JsonToObject {
public static void main(String[] args) {
Book book = new Book();
book.setId(1);
book.setPrice(125D);
book.setDescription("书本");
book.setWeight(10.5F);
// 将对象转换为json
String json = JSON.toJSONString(book);
System.out.println(json);
Book book1 = jsonToObject(json);
System.out.println(book1);
}
/**
* 将json转换为对象
* @param json
* @return
*/
private static Book jsonToObject(String json){
Book book = JSON.parseObject(json, Book.class);
return book;
}
}
3. Print the result
The conversion is OK!!
Welcome the big guys to leave a comment and learn together!!! Thanks!!!
===========================
Original article, reprinted with the source!