代码如下
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
public class TestFastJson {
public static void main(String[] args) {
// 转换成对象
String jsonstring = "{\"a\":51,\"b\":0}";
Usa u1 = JSON.parseObject(jsonstring, new TypeReference<Usa>(){});
Usa u2 = JSON.parseObject(jsonstring,Usa.class);
// 转换成对象数组
String jsonstring2 = "[{\"a\":51,\"b\":0}]";
Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference<Usa[]>(){});
List list = Arrays.asList(usa2);
// 转换成ArrayList
ArrayList<Usa> list2 = JSON.parseObject(jsonstring2, new TypeReference<ArrayList<Usa>>(){});
// 转换成ArrayList(默认) list3 与 list4 效果相同
ArrayList<JSONObject> list3 = JSON.parseObject(jsonstring2, new ArrayList<Usa>().getClass());
ArrayList<JSONObject> list4 = JSON.parseObject(jsonstring2, ArrayList.class);
for (int i = 0; i < list4.size(); i++) { // 推荐用这个
JSONObject io = list4.get(i);
System.out.println(io.get("a") + "======adn====="+io.get("b"));
}
}
}
class Usa {
private int count = 1888;
private String base = "project";
private Long a;
public Long getA() {
return a;
}
public void setA(Long a) {
this.a = a;
}
private String b;
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
json字符串 直接转换成List
ArrayList<Usa> usa2 = JSON.parseObject(jsonstring2, new TypeReference<ArrayList<Usa>>(){});
或者转换成对象数组
Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference<Usa[]>(){});
对象数组转List
List list = Arrays.asList(usa2);
我们使用new TypeReference的时候会生成多个class文件 里面有多少个new TypeReference 就会新增了class
即使我们在for循环里(0-N)写new TypeReference 这段代码也是多生成一个class文件,fastjson是看我们写了多少new TypeReference,而不是调用了多少次new TypeReference。推荐用ArrayList.class