专栏首页让技术和时代并行Gson在java中的简要使用

Gson在java中的简要使用

最近在把一个数组或字符串转化成对象时,使用了Google的Gson感觉不错,下面我以代码的形式详细举例来介绍

上面的注释部分为输出结果,使用了maven ,这里是Gson的maven依赖

 <dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2</version>
		</dependency> 
package gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

public class AllInAllGSON {
	   Gson gson = new Gson();//生成一个json对象
      @Test
      /**
       * [1,2,3,4,5,6,7,8,9,0] ["one","two","three","four","five","six","seven","eight","nine","zero"] [[1,2,3],[3,4,5],[4,5,6]]
       *  3 1n3 2n3 3n3 4n3 5n3 6n3 7n3 8n3 9n3 0n4 onen4 twon4 threen4 fourn4 fiven4 sixn4 sevenn4 eightn4 ninen4 zero data 1 data 2 data 3
       *data 3 data 4 data 5
        data 4 data 5 data 6
       */
      public void arrayToJson(){
    	  int [] n1 = {1,2,3,4,5,6,7,8,9,0};
    	  int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
    	  String [] n2 = {"one","two","three","four","five","six","seven","eight","nine","zero"}; 
    	 
    	  String x1 = gson.toJson(n1);//把数组转化成json
    	  String x2 = gson.toJson(n2);
    	  String x3 = gson.toJson(data);
    	  System.out.println(x1+ " "+ x2+" "+x3);
    	  int [] n3 = gson.fromJson(x1, int[].class);//把一个json转成数组
    	  String [] n4 = gson.fromJson(x2, String[].class);
    	  int [][] n5 = gson.fromJson(x3, int[][].class);
    	  for(int i=0;i<n3.length;i++){
    		  System.out.print("n3 "+n3[i]);
    	  }
    	  for(int i=0;i<n4.length;i++){
    		  System.out.print("n4 "+n4[i]);
    	  }
    	  for(int i=0;i<data.length;i++){
    		  for(int j=0;j<data[i].length;j++){
    			  System.out.print(" data "+data[i][j]);
    		  }
    		  System.out.println("");
    	  }
      }
      @Test
      /**
       * list ["hi","hello","how"]
       * [{"name":"Alice","address":"AppSt","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Baa St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
		name Alice
		name Bob
		name Carol
		name Mallory
       */
      public void listToJson(){
    	  List<String> list = new ArrayList<String>();//把一个list集合转化成json串
    	  list.add("hi");
    	  list.add("hello");
    	  list.add("how");
    	  String str = gson.toJson(list);
    	  System.out.println("list "+str);
    	  Student a = new Student("Alice", "AppSt", new Date(2000, 10, 1));
          Student b = new Student("Bob", "Baa St", null);
          Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
          Student d = new Student("Mallory", "Mango St", null);
          List<Student> student = new ArrayList<Student>();
          student.add(a);
          student.add(b);
          student.add(c);
          student.add(d);
          String str1 = gson.toJson(student);
          System.out.println(str1);
          Type type = new TypeToken<List<Student>>(){}.getType();//把json串转化成一个student对象
          List<Student> stu = gson.fromJson(str1, type);
          for(Student s:stu){
        	  System.out.println("name " + s.getName());
          }
      }
      @Test
      /**
       * {"WHITE":"5454#FFFFFF","BLUE":"0000FF","YELLOW":"sd#FFFF00","GREEN":"1008000","BLACK":"000000","RED":"#FeF0000"}
			map 5454#FFFFFF
			map 0000FF
			map sd#FFFF00
			map 1008000
			map 000000
			map #FeF0000
       */
      public void mapToJson(){
    	  Map<String, String> colours = new HashMap<String, String>();
          colours.put("BLACK", "000000");
          colours.put("RED", "#FeF0000");
          colours.put("GREEN", "1008000");
          colours.put("BLUE", "0000FF");
          colours.put("YELLOW", "sd#FFFF00");
          colours.put("WHITE", "5454#FFFFFF");
          String str = gson.toJson(colours);
          System.out.println(str);
          Type type = new TypeToken<Map<String,String>>() {}.getType();
          Map<String,String> map = gson.fromJson(str, type);
          for(String key:map.keySet()){
        	  System.out.println("map " + map.get(key));
          }
      }
      @Test 
      /**
       * {"name":"Bob","address":"Baa St"}
         Bob
       */
      public void stuClass(){
    	  Student b = new Student("Bob", "Baa St", null);//对一个类的属性进行转成json串  
    	  String str = gson.toJson(b);
    	  System.out.println(str);
    	  Student stu = gson.fromJson(str, Student.class);//把json转成java对象
    	  System.out.println(stu.getName());
      }
}

Student类

package gson;
import java.util.Date;

public class Student {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • c3p0的常用配置方式

    文件名字为:c3p0.properties(放在src目录下面) //程序我写的比较简单,可以用来测试执行配置。

    用户5166556
  • guava 集合和函数接口妙用

    用户5166556
  • Linux下tomcat使用

    http://tomcat.apache.org/download-70.cgi这里下载

    用户5166556
  • Python+Selenium笔记(七):WebDriver和WebElement

    (一)  WebDriver WebDriver提供许多用来与浏览器交互的功能和设置,通过WebDriver的功能和一些方法,来实现与浏览器窗口、警告、框架和弹...

    free赖权华
  • jsp 内置对象 登录 cookie + session

    mySoul
  • Swift 5.2 将KeyPaths用作函数

    Swift 5.2的新功能之一:能够将KeyPaths用作函数。如果您只在闭包中返回某个KeyPath的值,这将非常有用。

    韦弦zhy
  • 【BERT系列】—— 将Tensorflow格式的模型转换为Pytorch格式的模型

    以BERT为代表的预训练模型是目前NLP领域最火热的方向,但是Google发布的 BERT 是Tensorflow格式的,这让使用pytorch格式 程序猿 们...

    Dendi
  • 不要再认为Stream可读性不高了!

    距离Java 8发布已经过去了7、8年的时间,Java 14也刚刚发布。Java 8中关于函数式编程和新增的Stream流API至今饱受“争议”。

    用户1148394
  • Valve网站改版,将VR视为其未来的发展方向

    VRPinea
  • 理解BERT每一层都学到了什么

    本文解读ACL 2019最新收录的论文:What does BERT learn about the structure of language?

    zenRRan

扫码关注云+社区

领取腾讯云代金券