Java中java对象,Json,HashMap互相转化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//map转json字符串
HashMap<String, String>map = new HashMap<>();
map.put("name", "fyq");
map.put("age","18");
String jsonStr = JSON.toJSONString(map);
System.out.println("jsonStr===="+ jsonStr);
//对象转json字符串
Person person = new Person();
person.setName("gdm");
person.setAge("25");
String jsonStr1 = JSON.toJSONString(person);
System.err.println("jsonStr1===="+jsonStr1);
//json字符串转Map
String jsonStr2 = "{'age':'25','name':'gdm'}";
HashMap<String, String>map1 = new HashMap<>();
map1= JSON.parseObject(jsonStr2, HashMap.class);
System.err.println("map1===="+map1);
//json字符串转成对象
String jsonStr3 = "{'age':'25','name':'gdm'}";
Person person2 = new Person();
person = JSON.parseObject(jsonStr3, person.getClass());
System.err.println("pserson-name===="+ person.getName());

Pesrson:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Person {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!

分享
Fork me on GitHub