欢迎光临
一个有态度、有温度的分享型博客

使用google gson对json字符串和Java对象进行转换

使用google gson对json字符串和Java对象进行转换

java对象转换为json字符串

转换代码


/** * @author https://www.rxblog.xyz */ public class JavaToJsonDemo { public static void main(String[] args) { Person jack = new Person(); jack.setName("Jack"); jack.setAge(1); Person michael = new Person(); michael.setName("Michael"); jack.setAge(5); Gson gson = new Gson(); //示例1 System.out.println("================示例1=========="); System.out.println(gson.toJson(jack)); Company myCompany = new Company(); myCompany.setAddress("山东济南"); List<Person> personList = new ArrayList<>(); personList.add(jack); personList.add(michael); myCompany.setEmployees(personList); //示例2 System.out.println("================示例2=========="); System.out.println(gson.toJson(personList)); //示例3 System.out.println("================示例3=========="); System.out.println(gson.toJson(myCompany)); } }

输出结果

================示例1==========
{"name":"Jack","age":5}
================示例2==========
[{"name":"Jack","age":5},{"name":"Michael","age":0}]
================示例3==========
{"address":"山东济南","employees":[{"name":"Jack","age":5},{"name":"Michael","age":0}]}

json字符串转换为Java对象

转换代码

/**
 * @author https://www.rxblog.xyz
 */
public class JsonToJavaDemo {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Person michael = gson.fromJson("{\"name\":\"Michael\",\"age\":2}",Person.class);
        System.out.println(michael.getAge());
    }
}

输出结果

2

示例代码

https://github.com/cnmichaelw/gsonDemos

参考:

  1. https://my.oschina.net/itblog/blog/204120;
  2. http://qingkechina.blog.51cto.com/5552198/1290500;
  3. http://wl9739.github.io/2017/01/13/Gson-%E4%B8%AD%E6%96%87%E6%8C%87%E5%8D%97/;

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址