1、使用fastJson 将String转 map:
String out;
Object succesResponse = JSON.parse(out); //先转换成Object
Map map = (Map)succesResponse; //Object强转换为Map
2、String 转 Java 对象
fastjson 应用 string字符串转换成java对象或者对象数组
代码如下
- 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<Usa> list2 = JSON.parseObject(jsonstring2, new TypeReference<ArrayList<Usa>>(){});
-
-
- 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