当前位置: 首页 > 工具软件 > Gson > 使用案例 >

gson使用

逑翰翮
2023-12-01

1. pom依赖

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

2. javaBean转json字符串&json字符串转javaBean

// GsonBuilder 代替 new Gson() 可给出格式 

 /**
     * 将bean转换成Json字符串
     * @param bean
     * @return
     */
    public static String javaBeanToJson(Object bean) {
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setPrettyPrinting()
                .serializeNulls()
                .create().toJson(bean);
    }

    /**
     * 将Json字符串转换成对象
     * @param json
     * @param beanClass
     * @return
     */
    public static Object jsonToJavaBean(String json, Class beanClass) {
        return new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setPrettyPrinting().serializeNulls()
                .create().fromJson(json, beanClass);
    }  

3. 两个对象合并

BookStore bookStore = new BookStore();
bookStore.setId(1);
bookStore.setName("书籍");
bookStore.setCourseType(1);
bookStore.setCreateTime(new Date());

String bookStoreJson = javaBeanToJson(bookStore);
JsonObject returnData = JsonParser.parseString(bookStoreJson).getAsJsonObject();

//合并属性
 Page page = new Page();
 page.setPageNum(1);
 page.setPageSize(10);

String pageJson = javaBeanToJson(page);
JsonObject returnData2 = JsonParser.parseString(pageJson).getAsJsonObject();
returnData2.keySet()
		.forEach(key->{
            returnData.add(key, returnData2.get(key));
        });
        
//{"id":1,"name":"书籍","courseType":1,"createTime":"2022-04-15 17:11:46","updateTime":null,"field":null,"pageNum":1,"pageSize":10}        
System.out.println(returnData.toString());

4. gson反序列化Integer变为Double

Gson在使用ObjectTypeAdapter解析数值类型时,将其都当Double类型处理,而没有对类型进行细分处理。
Gson将Java中对应的double、long、int都统一为数值类型NUMBER

import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public class MapTypeAdapter extends TypeAdapter<Object> {
 
    @Override
    public Object read(JsonReader in) throws IOException {
        JsonToken token = in.peek();
        switch (token) {
            case BEGIN_ARRAY:
                List<Object> list = new ArrayList<Object>();
                in.beginArray();
                while (in.hasNext()) {
                    list.add(read(in));
                }
                in.endArray();
                return list;
 
            case BEGIN_OBJECT:
                Map<String, Object> map = new LinkedTreeMap<String, Object>();
                in.beginObject();
                while (in.hasNext()) {
                    map.put(in.nextName(), read(in));
                }
                in.endObject();
                return map;
 
            case STRING:
                return in.nextString();
 
            case NUMBER:
                /**
                 * 改写数字的处理逻辑,将数字值分为整型与浮点型。
                 */
               String numberStr = in.nextString();
                if (numberStr.contains(".") || numberStr.contains("e")
                        || numberStr.contains("E")) {
                    return Double.parseDouble(numberStr);
                }
                if (Long.parseLong(numberStr) <= Integer.MAX_VALUE) {
                    return Integer.parseInt(numberStr);
                }
                return Long.parseLong(numberStr);
 
            case BOOLEAN:
                return in.nextBoolean();
 
            case NULL:
                in.nextNull();
                return null;
 
            default:
                throw new IllegalStateException();
        }
    }
 
    @Override
    public void write(JsonWriter out, Object value) throws IOException {
        // 序列化无需实现
    }
}

//测试
String json = "{\"courseType\":1,\"createTime\":1650010418355,\"name\":\"书籍\",\"pageSize\":10,\"id\":1,\"pageNum\":1}";
Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<Map<String, Object>>() {}.getType(), new MapTypeAdapter()).create();
//map中数值正确
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());

 类似资料: