欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单使用Java Gson,list、map、实体类转换为json数据

程序员文章站 2022-06-15 14:17:30
...

首先导包Gson

maven:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>

gradle:

// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

然后我做了几个简单的数据,进行转换

package it.com.stu_demo08_08;

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

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test1 {
    //list-json
    @Test
    public void t1(){
        List<Object> list =new ArrayList<Object>();
        list.add(12);
        list.add("aaaaa");
        list.add(true);
        list.add(1.25);
        System.out.println("List:"+list.toString());
        //list转gson
        Gson gson=new Gson();
        String json=gson.toJson(list);
        System.out.println("json"+json);
        //gson转list
        List<Object> list2=gson.fromJson(json,new TypeToken<List<Object>>(){}.getType());
        System.out.println("List:"+list2.toString());
    }
    //map-json
    @Test
    public void t2(){
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("字符串","张山");
        map.put("int",10);
        map.put("boolean",false);
        System.out.println("map:"+map.toString());
        //map-gson
        Gson gson=new Gson();
        String json=gson.toJson(map);
        System.out.println("json:"+json);
        //gson-map
        Map<Object,Object> map2=gson.fromJson(json,new TypeToken<Map<Object,Object>>(){}.getType());
        System.out.println("map:"+map2);
    }
    //实体类-json
    @Test
    public void t3(){
        User user=new User();
        user.setId(1);
        user.setUsername("张山");
        System.out.println("bean:"+user);
        Gson gson=new Gson();
        //bean-json
        String json=gson.toJson(user);
        System.out.println("json:"+json);
        //json-bean
        User user1=gson.fromJson(json,new TypeToken<User>(){}.getType());
        System.out.println("bean:"+user1);
    }
}