使用FastJSON 对Map/JSON/String 进行互相转换
fastjson
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
项目地址:https://gitcode.com/gh_mirrors/fastj/fastjson
·
1.String 转 Json
@Test
public void test(){
String str = "{\"age\":\"24\",\"name\":\"hekliu\"}";
JSONObject jsonObject = JSONObject.parseObject(str);
System.out.println("json对象是:" + jsonObject);
Object object = jsonObject.get("name");
System.out.println("name值是:" + object);
}
运行结果:
json对象是:{"name":"hekliu","age":"24"}
name值是:hekliu
2.Json 转 String
@Test
public void test(){
String str = "{\"age\":\"24\",\"name\":\"hekliu\"}";
JSONObject jsonObject = JSONObject.parseObject(str);
//json对象转字符串
String jsonString = jsonObject.toJSONString();
System.out.println("json字符串是:" + jsonString);
}
运行结果:
json字符串是:{"name":"hekliu","age":"24"}
3.String 转 Map
@Test
public void test(){
String str = "{\"age\":\"24\",\"name\":\"hekliu\"}";
JSONObject jsonObject = JSONObject.parseObject(str);
//json对象转Map
Map<String, Object> map = (Map<String, Object>)jsonObject;
System.out.println("map对象是:" + map);
Object object = map.get("age");
System.out.println("age的值是" + object);
}
运行结果:
map对象是:{"name":"hekliu","age":"24"}
age的值是24
4.Map 转 String
@Test
public void test(){
Map<String,Object> map = new HashMap<>();
map.put("age", 24);
map.put("name", "hekliu");
String jsonString = JSON.toJSONString(map);
System.out.println("json字符串是:" + jsonString);
}
运行结果:
json字符串是:{"name":"hekliu","age":24}
5.Map 转 Json
@Test
public void test(){
Map<String,Object> map = new HashMap<>();
map.put("age", 24);
map.put("name", "hekliu");
JSONObject json = new JSONObject(map);
System.out.println("Json对象是:" + json);
}
运行结果:
Json对象是:{"name":"hekliu","age":24}
6.Json 转 Map
见示例3
7.对象与字符串之间的互转
//将对象转换成为字符串
String str = JSON.toJSONString(infoDo);
//字符串转换成为对象
InfoDo infoDo = JSON.parseObject(strInfoDo, InfoDo.class);
8.对象集合与字符串之间的互转
//将对象集合转换成为字符串
String users = JSON.toJSONString(users);
//将字符串转换成为对象集合
List<User> userList = JSON.parseArray(userStr, User.class);
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:4 个月前 )
c942c834 - 2 年前
5bc4709b - 2 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)