1.导入hutool工具依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
2.直接复制一下代码运行
import cn.hutool.json.JSONUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception{
Map<String,String> map = new HashMap<>();
map.put("host","127.0.0.1");
map.put("port","1433");
map.put("username","xu");
map.put("password","123456");
//将map转json字符串
String jsonStr = JSONUtil.toJsonStr(map);
System.out.println("jsonStr:"+jsonStr);
//将json字符串转map
Map<String,String> jsonStrTomap = JSONUtil.toBean(jsonStr, Map.class);
System.out.println("jsonStrTomap:"+jsonStrTomap);
Person person = new Person();
person.setAge(18);
person.setName("妹妹今年18岁");
//将person对象转json字符串
String personJSonStr = JSONUtil.toJsonStr(person);
System.out.println("personJSonStr:"+personJSonStr);
//将person字符串转换回person对象
Person personFromJsonStr = JSONUtil.toBean(personJSonStr, Person.class);
System.out.println("personFromJsonStr:"+personFromJsonStr);
//person对象集合转json字符串
List<Person> personList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person p = new Person();
p.setAge(18+i);
p.setName("妹妹今年"+p.getAge()+"岁");
personList.add(p);
}
//将集合对象转json字符串
String personListJsonStr = JSONUtil.toJsonStr(personList);
System.out.println("personListJsonStr:"+personListJsonStr);
//再将json字符串转回到对象集合
List<Person> personListFromJsonStr = JSONUtil.toList(personListJsonStr, Person.class);
System.out.println("personListFromJsonStr:"+personListFromJsonStr);
}
static class Person {
public String name;
public int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}