首先,在下载FastJson插件,添加到项目中
随后进行实现
public class TestFastJson {
public static void main(String[] args) {
User u =new User();
u.setId(10);
u.setUsername("softeem");
u.setPassword("123456");
u.setVip(true);
//1.将java对象转换为json字符串
String json = JSON.toJSONString(u);
System.out.println(json);
//2.讲一个json字符串转换为字符串
json ="{\"id\":20,\"password\":\"6666\",\"username\":\"admin\",\"vip\":false}";
u = JSON.parseObject(json, User.class);
System.out.println(u);
//3.如何将集合转换为json字符串
List<User> list =new ArrayList<>();
list.add(new User(1,"softeem","123456",true));
list.add(new User(2,"亚索","123456",true));
list.add(new User(3,"提莫","123456",true));
list.add(new User(4,"布兰德","123456",false));
json=JSON.toJSONString(list);
System.out.println(json);
//4.将json数组转换为java集合
list= JSON.parseArray(json, User.class);
System.out.println(list);
//5.若解析的json字符串找不到对应的java类时?
String json2="{\"sid\":10,\"name\":\"孙悟空\"}";
//将json自渡船解析为java对象,JSONObject实际上就是一个Map集合
JSONObject obj =JSON.parseObject(json2);
Integer sid = obj.getInteger("sid");
String name = obj.getString("name");
System.out.println(sid+"---"+name);
}
}