List对象集合与Json String怎样互转

JSON工具包有很多,比如FastJSON、GJson等,本文用FastJSON工具包实现如下两个功能。

  1. JSON字符串转List<JavaBean>集合
  2. List<JavaBean>集合怎样转JSON

 

第一步:引入FastJson包

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.31</version>

</dependency>

 

第二步:创建一个javaBean对象

 

package site.sharebook.xiangqing.Bean;

/**

* <p></p>

* @author guanxiangqing 2017年04月13日 20:27

* @version V1.0

*/

public class Book {

private String bookName;

private float price;

public String getBookName() {

return bookName;

}

public void setBookName(String bookName) {

this.bookName = bookName;

}

public float getPrice() {

return price;

}

public void setPrice(float price) {

this.price = price;

}

}

第三步:编写测试方法

package site.sharebook.xiangqing.Test;

import com.alibaba.fastjson.JSON;

import site.sharebook.xiangqing.Bean.Book;

import java.util.ArrayList;

import java.util.List;

/**

* <p></p>

* @author guanxiangqing 2017年04月13日 20:26

* @version V1.0

*/

public class JsonToStringOrStringToJsonTest {

public static void main(String[] args) {

List<Book> list = new ArrayList<Book>();

Book book = new Book();

book.setBookName("Data Algorithm");

book.setPrice(56.0f);

list.add(book);

 

Book book2 = new Book();

book2.setBookName("Spark in Action");

book2.setPrice(60.0f);

list.add(book2);

 

Book book3 = new Book();

book3.setBookName("Flink in Action");

book3.setPrice(66.0f);

list.add(book3);

 

/**

* 集合对象转换为JSON字符串

*/

String jsonString = JSON.toJSONString(list);

System.out.println("jsonString:" + jsonString);

//返回的结果为:jsonString:[{"bookName":"Data Algorithm","price":56.0},{"bookName":"Spark in Action","price":60.0},{"bookName":"Flink in Action","price":66.0}]

 

/**

* JSON字符字符串转变成List对象集合

*/

List<Book> list2 = JSON.parseArray(jsonString,Book.class);

int i = 1;

for(Book data: list2){

System.out.print("第" + i + "本书书名:" + data.getBookName());

System.out.print(" ");

System.out.println(" 价格:" + data.getPrice());

i++;

}

/**

* 上面For循环骤返回的结果:

*

* 1本书书名:Data Algorithm  价格:56.0

* 第2本书书名:Spark in Action  价格:60.0

* 第3本书书名:Flink in Action  价格:66.0

*

*/

}

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: