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 map = (Map)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 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 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 userList = JSON.parseArray(userStr, User.class);