package fastJsonOpera;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.User;
import org.junit.Test;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class FastJsonOpera {
/**
* 将实体类转化为json字符串
*/
@Test
public void test(){
User user = new User("hanchao","0",23);
String s = JSON.toJSONString(user);
System.out.println(s); //{"age":23,"male":"0","name":"hanchao"}
}
/**
* 将map转化为json字符串
*/
@Test
public void test1(){
Map<String,User> map = new HashMap<>();
map.put("1",new User("hanchao","0",23));
map.put("2",new User("hctrl","0",23));
String s = JSON.toJSONString(map);
System.out.println(s); //{"1":{"age":23,"male":"0","name":"hanchao"},"2":{"age":23,"male":"0","name":"hctrl"}}
}
/**
* 将list转化为json字符串
*/
@Test
public void test2(){
List<User> list = new LinkedList<>();
list.add(new User("hanchao","0",23));
list.add(new User("hctrl","0",23));
String s = JSON.toJSONString(list);
System.out.println(s); //[{"age":23,"male":"0","name":"hanchao"},{"age":23,"male":"0","name":"hctrl"}]
}
/**
* 将json字符串转化为实体类
*/
@Test
public void test3(){
User user = new User("hanchao","0",23);
String s = JSON.toJSONString(user);
JSONObject jsonObject = JSON.parseObject(s);
System.out.println(jsonObject); //{"age":23,"male":"0","name":"hanchao"}
String name = jsonObject.getString("name");
System.out.println(name); //hanchao
User user1 = JSON.parseObject(s, User.class);
System.out.println(user1); //User(name=hanchao, male=0, age=23)
}
/**
* 将json字符串转化为JSONObject
*/
@Test
public void test4(){
Map<String,User> map = new HashMap<>();
map.put("1",new User("hanchao","0",23));
map.put("2",new User("hctrl","0",23));
String s = JSON.toJSONString(map);
Map<String,User> parse = JSON.parseObject(s,Map.class);
User user = JSON.parseObject(JSON.toJSONString(parse.get("1")),User.class);
System.out.println(user);
}
/**
* 将json字符串转化为list集合
*/
@Test
public void test5(){
List<User> list = new LinkedList<>();
list.add(new User("hanchao","0",23));
list.add(new User("hctrl","0",23));
String s = JSON.toJSONString(list);
List<User> users = JSON.parseArray(s, User.class);
users.forEach(System.out::println); //User(name=hanchao, male=0, age=23)User(name=hctrl, male=0, age=23)
}
/**
* 将Map转成JSONObject
*/
@Test
public void test6(){
Map<String,Object> map = new HashMap<>();
map.put("1",new User("hanchao","0",23));
map.put("2",new User("hctrl","0",23));
JSONObject jsonObject = new JSONObject(map);
Object o = jsonObject.get("1");
System.out.println(o); //User(name=hanchao, male=0, age=23)
}
@Test
public void test7(){
Map<String,JSONObject> map = new HashMap<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","hanchao");
jsonObject.put("male","0");
jsonObject.put("age",23);
map.put("1",jsonObject);
String s = JSON.toJSONString(map);
Map<String,JSONObject> map1 = JSON.parseObject(s, Map.class);
System.out.println(map1.get("1").getString("name"));
}
}
fastjson常用操作
最新推荐文章于 2022-03-29 10:50:12 发布