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 u2 = JSON.parseObject(jsonstring,Usa.class);
// 转换成对象数组
String jsonstring2 = "[{\"a\":51,\"b\":0}]";
Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference(){});
List list = Arrays.asList(usa2);
// 转换成ArrayList
ArrayList list2 = JSON.parseObject(jsonstring2, new TypeReference>(){});
// 转换成ArrayList(默认) list3 与 list4 效果相同
ArrayList list3 = JSON.parseObject(jsonstring2, new ArrayList().getClass());
ArrayList list4 = JSON.parseObject(jsonstring2, ArrayList.class);
for (int i = 0; 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 usa2 = JSON.parseObject(jsonstring2, new TypeReference>(){});
或者转换成对象数组
Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference(){});
对象数组转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