今天,我们来介绍一下Gson的jar包的用法.

JSON解析之Gson

特点:编码简介,谷歌官方推荐

数据之间的转换:

  1.将json格式的字符串{}转换成为java对象

  API:
    <T> T fromJson(String json,Class<T> classOfT);
    注意:要求json对象中的key的名称与java对象对应的类中的属性名要相同

  步骤:
    1.将Gson的jar包导入到项目中
    2.创建Gson对象:
      Gson gson = new Gson();
    3.通过创建的Gson对象调用fromJson()方法,返回该JSON数据对应的java对象:
      ShopInfo shopInfo = gson.fromJson(json,ShopInfo.class);

  代码:

    a.gson中所对应的类:

    

public class ShopInfo {
   private int id;
   private String name;
   private double price;
   private String imagePath;    public ShopInfo() {
   }    public ShopInfo(int id, String name, double price, String imagePath) {
this.id = id;
this.name = name;
this.price = price;
this.imagePath = imagePath;
   }    public int getId() {
return id;
   }    public void setId(int id) {
this.id = id;
   }    public String getName() {
return name;
   }    public void setName(String name) {
this.name = name;
   }    public double getPrice() {
return price;
   }    public void setPrice(double price) {
this.price = price;
   }    public String getImagePath() {
return imagePath;
   }    public void setImagePath(String imagePath) {
this.imagePath = imagePath;
   }    @Override
   public String toString() {
return "ShopInfo{" +
  "id=" + id +
  ", name='" + name + '\'' +
  ", price=" + price +
  ", imagePath='" + imagePath + '\'' +
  '}';
   }
}

  b.解析json方法:

public class One {
  public static void main(String[] args) {
String json = "{\n" +
    "\"id\":2,\n" +
    "\"name\":\"大虾\",\n" +
    "\"price\":23.3,\n" +
    "\"imagePath\":\"http://www.baidu.com\"\n" +
    "}";
Gson gson = new Gson();
ShopInfo shopInfo = gson.fromJson(json, ShopInfo.class);
System.out.println(shopInfo.toString());
  }
}

  

  2.将json格式的字符串[]转化为java对象的List

    API:
      fromJson(String json,Type typeOfT);
    步骤:
      1.将Gson的jar包导入到项目中
      2.创建Gson对象:Gson gson = new Gson();
      3.通过创建的Gson对象调用fromJson()方法,返回该JSON数据对应的java集合:
        List<ShopInfo> shops = gson.fromJson(json,new TypeToken<List<ShopInfo>>(){}.getType());

    代码:

      

public class Two {
  public static void main(String[] args) {
String json = "[\n" +
" {\n" +
" \"id\":1,\n" +
" \"imagePath\":\"http://www.baidu.com\",\n" +
" \"name\":\"大虾1\",\n" +
" \"price\":12.3\n" +
" },\n" +
" {\n" +
" \"id\":2,\n" +
" \"imagePath\":\"http://www.douban.com\",\n" +
" \"name\":\"大虾2\",\n" +
" \"price\":12.5\n" +
" }\n" +
"]";
Gson gson = new Gson();
List<ShopInfo> shops = gson.fromJson(json, new TypeToken<List<ShopInfo>>() {
  }.getType());
for (int i = 0; i <shops.size() ; i++) {
  System.out.println(shops.toString());
}
  }
}

  

  3.将java对象转换为json字符串{}

  

    API:
      String toJson(Object src);
    步骤:
      1.将Gson的jar包导入到项目中
      2.创建Gson对象:
        Gson gson = new Gson();
      3.通过创建的Gson对象调用toJson()方法,返回json数据;
        ShopInfo shop = new ShopInfo(1,"鲍鱼",250.0,"");
        String json = gson.toJson(shop);

    代码:   

public class Three {
  public static void main(String[] args) {
Gson gson = new Gson();
ShopInfo shopInfo = new ShopInfo(1, "鲍鱼", 250.0, "");
String json = gson.toJson(shopInfo);
System.out.println(json);
  }
}

  

  4.将java对象的List转换为json字符串[]
    API:
      String toJson(Object src);
    步骤:
      1.将Gson的jar包导入到项目中
      2.创建Gson对象:
        Gson gson = new Gson();
      3.通过创建的Gson对象调用toJson()方法,返回json数据:
        List<ShopInfo> shops = new ArrayList<>();
        String json = gson.toJson(shops);

public class Four {
  public static void main(String[] args) {
ArrayList<ShopInfo> shopInfos = new ArrayList<ShopInfo>();
ShopInfo shopInfo1 = new ShopInfo(1, "鲍鱼1", 250.0, "");
ShopInfo shopInfo2 = new ShopInfo(2, "鲍鱼2", 250.2, "");
shopInfos.add(shopInfo1);
shopInfos.add(shopInfo2);
Gson gson = new Gson();
String json = gson.toJson(shopInfos);
System.out.println(json);
  }
}

  

  最后在贴一下gson的maven的依赖

  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.7</version>
  </dependency>

JSON初体验(二):Gson解析的更多相关文章

  1. JSON初体验(三):FastJson解析

    JSON解析之FastJson(阿里巴巴解析开源) 特点: Fastjson是一个Java语言编写的高性能功能完善的JSON库,它采用的 是一种"假定有序快速匹配"的算法,把JSO ...

  2. JSON初体验(一):JsonObject解析

    在学校的呆了一段时间,马上又要回去工作了,不说了,我现在介绍一下json相关的内容 1.JSON数据格式(总的来说,json就是一个字符串) 1.整体结构 String json1 = "{ ...

  3. SpringBoot初体验及原理解析

    一.前言 ​ 上篇文章,我们聊到了SpringBoot得以实现的幕后推手,这次我们来用SpringBoot开始HelloWorld之旅.SpringBoot是Spring框架对“约定大于配置(Conv ...

  4. Ruby on rails初体验(二)

    体验一中添加了一个最基本的支架和一个简单的数据迁移,实现了一个基本的增删改查的功能列表.体验二中要在次功能上继续丰满一下功能.实现如下效果: 在每个公司中都包含有不同的部门,按照体验一中的方法,添加一 ...

  5. 【原创】Jquery初体验二

    快速导航 一.传统方式生成Table 二.使用jquery.tmpl插件快速生成Table 三.Jquery中的操作class的几个方法 四:jq里面的克隆 五:属性过滤器 六:表单元素过滤器 一.传 ...

  6. Spring Cloud Alibaba 初体验(二) Nacos 服务注册与发现 + 集成 Spring Cloud Gateway

    一.服务注册 添加依赖: <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>s ...

  7. node初体验(二)

    1.静态资源访问,需要设置路由和响应标头 2.url模块.path模块.querystring模块 Url { protocol: null, slashes: null, auth: null, h ...

  8. jquery.fn.extend与jquery.extend--(初体验二)

    1.jquery.extend(object); 为扩展jQuery类本身.为类添加新的方法. jquery.fn.extend(object);给jQuery对象添加方法. $.extend({ a ...

  9. Google Gson解析Json数据应用实例

    转自:http://lixigao449778967.blog.163.com/blog/static/24985164201269105928783/ 1.需要的Jar包 1) Google Gso ...

随机推荐

  1. 用python管理Cisco路由器

    目前DevOps是整个运维发展的方向,Network的运维也一样.使用程序控制底层的路由器是最基本的要求之一. 本文简单解释如何用Python控制路由器,对网络设备进行配置. Python和网络设备连 ...

  2. git多站点多用户情况下SSH配置

    个人使用github,但是公司使用的是 GitLab .那么在一个电脑上进行处理时,由于先设置了 github 的,导致没办法从 GitLab 上处理 git .其实是由于 ssh 的问题. 下面记录 ...

  3. Hibernate中一对多关联关系中的级联属性

    如果想通过级联属性删除一端的数据和多端的数据要使用 void org.hibernate.Session.delete(Object arg0) 方法. getSession().delete(tea ...

  4. ZJOI2019Day1镇海中学游记(3.24~3.27)

    前言 第一次正式参加省选!不管怎么说,虽然明知自己很弱,但还是要尽力去尝试吧! 最好能进前\(100\),不然就没法去\(Day2\)了. \(Mar\ 24th\):出发 今天,我们正式从二中向宁波 ...

  5. HDU 1216 Assistance Required(暴力打表)

    传送门: http://acm.hdu.edu.cn/showproblem.php?pid=1216 Assistance Required Time Limit: 2000/1000 MS (Ja ...

  6. MVC5 数据注解和验证

    ①利用数据注解进行验证 ②创建自定义的验证逻辑 ③模型元数据注解的用法 ①先创建数据源 1,创建我们的Model  Order 2,创建控制器带EF 选择模型为Order 当你运行的时候会报错,需要代 ...

  7. 关于ProjectServer调用PSI 报Error GeneralReadOnlyColumn (20005) - column TS_ACT_FINISH_DATE错的解决方案

    TimesheetDataSet Table Actuals Row: TS_LINE_UID='f4b970f8-fb03-44d1-9997-cd31da42cb09' TS_ACT_START_ ...

  8. Restrramework源码(包含组件)分析

    1.总体流程分析 rest_framework/view.py 请求通过url分发,触发as_view方法,该方法在ViewSetMixin类下 点进去查看as_view源码说明,可以看到它在正常情况 ...

  9. plupload批量上传分片(后台代码)

    plupload批量上传分片功能, 对于文件比较大的情况下,plupload支持分片上传,后台代码如下: /** * * 方法:upLoadSpecialProgramPictrue * 方法说明:本 ...

  10. css选择器有哪些

    css的选择器是还是比较富的,主要的css选择器如下: 标签选择器(如:body,div,p,ul,li) .类选择器(如:class="head",class="hea ...