一、gson
1.将对象转换为JSON字符串
转换JSON字符串的步骤:
- 引入JAR包
- 在需要转换JSON字符串的位置编写如下代码即可:
String json = new Gson().toJSON(要转换的对象)
代码如下(示例):
public class Demo1 {
public static void main(String[] args) {
Game g = new Game("ff14","mmorpg","日本");
String s = new Gson().toJson(g);
System.out.println(s);
}
static class Game{
private String name;
private String type;
private String country;
public Game(String name, String type, String country) {
this.name = name;
this.type = type;
this.country = country;
}
}
}
运行结果:
{“name”:“ff14”,“type”:“mmorpg”,“country”:“日本”}
2.将JSON字符串转换为对象
- 引入JAR包
- 在需要转换Java对象的位置, 编写如下代码:
对象 = new Gson().fromJson(JSON字符串,对象类型.class) - 如果不存在相应的对象可以创建map类型,示例:
map类型 = new Gson().fromJson(JSON字符串,map类型.class)
代码如下(示例):
public class Demo2 {
public static void main(String[] args) {
//1. 创建Gson对象
Gson g = new Gson();
//2. 转换 : {"name":"ff14","type":"mmorpg","country":"日本"}
Game game = g.fromJson("{\"name\":\"ff14\",\"type\":\"mmorpg\",\"country\":\"日本\"}", Game.class);
System.out.println(game.getName());
}
static class Game{
private String name;
private String type;
private String country;
public Game(String name, String type, String country) {
this.name = name;
this.type = type;
this.country = country;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getCountry() {
return country;
}
}
}
二、fastjson
1.将对象转换为JSON字符串
转换JSON字符串的步骤:
- 引入JAR包
- 在需要转换JSON字符串的位置编写如下代码即可:
String json=JSON.toJSONString(要转换的对象);
代码如下(示例):
public class Demo4 {
public static void main(String[] args) {
Game game = new Game("ff14","mmorpg","日本");
//1. 转换
String json = JSON.toJSONString(game);
System.out.println(json);
}
static class Game{
private String name;
private String type;
private String country;
public Game(String name, String type, String country) {
this.name = name;
this.type = type;
this.country = country;
}
public Game() {
}
@Override
public String toString() {
return "Game{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", country='" + country + '\'' +
'}';
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getCountry() {
return country;
}
}
}
2.将JSON字符串转换为对象
- 引入JAR包
- 在需要转换Java对象的位置, 编写如下代码:
类型 对象名=JSON.parseObject(JSON字符串, 类型.class);
或 List<类型> list=JSON.parseArray(JSON字符串,类型.class);
代码如下(示例):
public class Demo5 {
public static void main(String[] args) {
//1. 转换 : {"country":"日本","name":"ff14","type":"mmorpg"}
Game game = JSON.parseObject("{\"country\":\"日本\",\"name\":\"ff14\",\"type\":\"mmorpg\"}", Game.class);
System.out.println(game.getName());
}
}
//内部类存在些许问题fistjson,无get方法,对象转json就是空,而用内部类json转对象会出错。