gson读取json字符串_使用 Gson 实现 Json 字符串和 Java 对象之间的相互转换

简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

依赖

com.google.code.gson

gson

2.6.2

关于这个话题,需要注意的细节还是有一些的,这里只是结合自身需要整理了最基本的用法。如果想要了解更多细节性的问题,可以参考 http://www.jianshu.com/p/e740196225a4 (怪盗kidou)系列文章。

一、Json 字符串转换为 Java 对象

假设我们有如下的 json 字符串:

{

"id": "001",

"name": "zhangsan",

"score": 90,

"hobbies": [

"soccer",

"chess"

]

}

若要将一个 json 字符串转换为一个 java 对象,我们首先需要编写与该 json 字符串相应的 java 类,如下:

public class Student {

private String id;

private String name;

private int score;

private List hobbies = new ArrayList<>();

// getter and setter methods are omitted here.

@Override

public String toString() {

return "Student [id=" + id + ", name=" + name + ", score=" + score + ", hobbies=" + hobbies + "]";

}

}

将以上 json 字符串转换为 Student 对象的方式很简单,代码如下:

public class GsonDemo {

public static void main(String[] args) {

String jsonStr = "{\"id\": \"001\", \"name\": \"zhangsan\", \"score\": 90, \"hobbies\": [\"soccer\", \"chess\"]}";

Gson gson = new Gson();

Student student = gson.fromJson(jsonStr, Student.class);

System.out.println(student);

}

}

代码执行结果如下:

Student [id=001, name=zhangsan, score=90, hobbies=[soccer, chess]]

存在的问题

对于上面的实现方式,我们发现,json 字符串中的各个 key(键) 和定义的 Student 类中的各个属性名都是对应相同的,如 json 字符串中有 id,name,score 和 hobbies 四个 key,同时在 Student 类中定义了四个属性,名称也是 id,name,score 和 hobbies。这种情况下,以上的代码执行的结果完全符合我们的预期。但如果 Student 类中定义的属性名称分别是 id,name,marks 和 hobbies,即 json 字符串中的 key 和 Student 类中的属性名不是完全对应相同的情况下,以上代码的执行结果却是

Student [id=001, name=zhangsan, marks=0, hobbies=[soccer, chess]]

我们发现 marks 属性没有被转换。

解决方案

对于上面存在的问题,我们的解决方式是使用注解。现在我们将给 Student 类的 marks 属性加上注解,代码如下:

public class Student {

private String id;

private String name;

@SerializedName("score")

private int marks;

private List hobbies = new ArrayList<>();

// getter and setter methods are omitted here.

@Override

public String toString() {

return "Student [id=" + id + ", name=" + name + ", marks=" + marks + ", hobbies=" + hobbies + "]";

}

}

我们再次执行客户端代码,结果如下:

Student [id=001, name=zhangsan, marks=90, hobbies=[soccer, chess]]

发现在 Student 类中给 marks 属性加上注解之后,该属性可以被正常转换了。

二、Java 对象转换为 Json 字符串

将 Java 对象转换为 Json 字符串相对来说简单一些,代码如下:

Student 类:

public class Student {

private String id;

private String name;

@SerializedName("score")

private int marks;

private List hobbies = new ArrayList<>();

public Student(String id, String name, int marks, List hobbies) {

this.id = id;

this.name = name;

this.marks = marks;

this.hobbies = hobbies;

}

// getter and setter methods are omitted here.

@Override

public String toString() {

return "Student [id=" + id + ", name=" + name + ", marks=" + marks + ", hobbies=" + hobbies + "]";

}

}

客户端代码:

public class GsonDemo {

public static void main(String[] args) {

List hobbies = Arrays.asList("soccer", "chess");

Student student = new Student("001", "zhangsan", 90, hobbies);

Gson gson = new Gson();

String jsonStr = gson.toJson(student);

System.out.println(jsonStr);

}

}

执行结果如下:

{"id":"001","name":"zhangsan","score":90,"hobbies":["soccer","chess"]}

注意:我们发现,Student 类中的属性 marks 在转换为 json 字符串后,对应的是 json 字符串中的 score 。也就是说 @SerializedName 注解在将 java 对象转换为 json 字符串的过程中也是起作用的。

额外注意点

1、从文件中读取 json 字符串并转换为 java 对象

json 文件内容如下:

{

"id": "001",

"name": "zhangsan",

"score": 90,

"hobbies": [

"soccer",

"chess"

]

}

客户端代码如下:

public class GsonDemo {

public static void main(String[] args) throws Exception {

Gson gson = new Gson();

Student student = gson.fromJson(new FileReader("file.json"), Student.class);

System.out.println(student);

}

}

2、格式化输出 json 字符串

只需要将

Gson gson = new Gson();

改为

Gson gson = new GsonBuilder().setPrettyPrinting().create();

json 字符串输出效果如下:

{

"id": "001",

"name": "zhangsan",

"score": 90,

"hobbies": [

"soccer",

"chess"

]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值