FastJson的相互转换

首先在使用FastJson时,先去导入jar包,这个jar是阿里巴巴开源的,我们可以到maven仓库中下载.

这是我的测试类:

  

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dao.Customer;
import com.dao.Person;
import com.dao.Role;

public class TestFastJson {

/*
* 对象转换成json字符串
*/
@Test
public void run1() {

Customer customer = new Customer();

customer.setId(100);

customer.setName("Agust");

String jsonString = JSON.toJSONString(customer);

System.out.println(jsonString);

}

/*
* json字符串转换成对象
*/
@Test
public void run2() {
String jsonString = "{\"id\":100,\"name\":\"Agust\"}";

Customer object = JSON.parseObject(jsonString, Customer.class);

System.out.println(object);
}

/*
* 添加同一个对象时 禁止使用引用地址$ref:[{"id":100,"name":"Agust"},{"$ref":"$[0]"}]
*
*/
@Test
public void run3() {

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

Customer customer = new Customer();

customer.setId(100);

customer.setName("Agust");

list.add(customer);

list.add(customer);

String jsonString = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);

System.out.println(jsonString);

}

/*
* json数组转换成实体集合
*
*/
@Test
public void run4() {

String jsonString = "[{\"id\":100,\"name\":\"Agust\"},{\"id\":100,\"name\":\"Agust1\"}]";

List<Customer> parseArray = JSON.parseArray(jsonString, Customer.class);
for (Customer customer : parseArray) {
System.out.println(customer);
}

}

/*
*
* Person中引用Role,在Role中引用了Person
*
* 防止循环引用造成栈内存溢出,在实体中加入注解
*
* @JSONField(serialize = false) 禁止循环引用
*
*/

@Test
public void run5() {

Person person = new Person();

person.setName("小子");

Role role = new Role();

role.setName("姑娘");

person.setrName(role);

role.setpName(person);

String jsonString = JSON.toJSONString(role, SerializerFeature.DisableCircularReferenceDetect);

System.out.println(jsonString);

}

}

下面是我测试需要的三个实体类


public class Customer {

private int id;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

private String name;


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + "]";
}
}


import com.alibaba.fastjson.annotation.JSONField;

public class Person {


private String name;
//这是为了阻止循环引用
@JSONField(serialize = false)
private Role rName;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Role getrName() {
return rName;
}

public void setrName(Role rName) {
this.rName = rName;
}

}


public class Role {

private String name;

private Person pName;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Person getpName() {
return pName;
}

public void setpName(Person pName) {
this.pName = pName;
}

}

猜你喜欢

转载自www.cnblogs.com/AugustMu/p/9700553.html
今日推荐