Jfinal利用Gson序列化Model和Record

foxlee 发布于 2015/05/01 18:02
阅读 1K+
收藏 1

    用JFinal做过一些开发,对于toJson方法进行了 一些定制,用上了以前常用的Gson包来序列化Model和Record对象,拿出来献丑了,希望大家多多提意见!

    首先要开发两个ModelAdapter和RecordAdapter适配器,来定制化Model和Recordd的序列化。


package com.jfinal.kit;

import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.jfinal.plugin.activerecord.CPI;
import com.jfinal.plugin.activerecord.Model;
import java.lang.reflect.Type;

/**
 * Created by EricLee on 2014/9/10.
 */
public class ModelAdapter implements JsonSerializer<Model> {
  @Override
  public JsonElement serialize(Model model, Type type, JsonSerializationContext context) {
    return context.serialize(CPI.getAttrs(model));
  }
}



package com.jfinal.kit;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.jfinal.plugin.activerecord.Record;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by EricLee on 2014/9/10.
 */
public class RecordAdapter implements JsonSerializer<Record>, JsonDeserializer<Record> {
  @Override
  public Record deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
    Record r = new Record();
    Map<String, Object> m = context.deserialize(jsonElement, HashMap.class);
    r.setColumns(m);
    return r;
  }

  @Override
  public JsonElement serialize(Record record, Type type, JsonSerializationContext context) {
    return context.serialize(record.getColumns());
  }
}



然后改造JsonKit对象



/**
 * Copyright (c) 2011-2012, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jfinal.kit;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import java.io.Reader;
import java.lang.reflect.Type;

/**
 * Convert object to json string.
 *
 * Json     			java string			java.lang.String number			java.lang.Number true|false		java.lang.Boolean null				null array			java.util.List object			java.util.Map
 */
public class JsonKit {
  /**
   * 默认的 {@code JSON} 日期/时间字段的格式化模式。
   */
  public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH🇲🇲ss";
  private static final Gson GSON = createGson(true);
  private static final Gson GSON_NO_NULLS = createGson(false);

  /**
   * Create the standard {@link com.google.gson.Gson} configuration
   *
   * @return created gson, never null
   */
  public static final Gson createGson() {
    return createGson(true);
  }

  /**
   * Create the standard {@link com.google.gson.Gson} configuration
   *
   * @param serializeNulls whether nulls should be serialized
   * @return created gson, never null
   */
  public static final Gson createGson(final boolean serializeNulls) {
    final GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Record.class, new RecordAdapter());
    builder.registerTypeHierarchyAdapter(Model.class, new ModelAdapter());
    builder.setDateFormat(DEFAULT_DATE_PATTERN);//设置JSON格式化的日期格式
    /*builder.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
    builder.excludeFieldsWithoutExposeAnnotation();
    if (serializeNulls) {
      builder.serializeNulls();
    }
    return builder.create();
  }

  public static final Gson getGson() {
    return GSON;
  }

  public static final Gson getGson(final boolean serializeNulls) {
    return serializeNulls ? GSON : GSON_NO_NULLS;
  }

  public static final String toJson(final Object object) {
    return toJson(object, false);
  }

  public static final String toJson(final Object object, final boolean includeNulls) {
    return includeNulls ? GSON.toJson(object) : GSON_NO_NULLS.toJson(object);
  }

  public static String toJson(Object target, String datePattern) {
    final GsonBuilder builder = new GsonBuilder();
    if (datePattern == null || datePattern.length() <= 0) {
      datePattern = DEFAULT_DATE_PATTERN;
    }
    builder.setDateFormat(datePattern);
    return builder.create().toJson(target);
  }

  public static String toJson(Object target, Type targetType) {
    return GSON_NO_NULLS.toJson(target, targetType);
  }

  public static final <V> V parse(String json, Class<V> type) {
    return GSON.fromJson(json, type);
  }

  public static final <V> V parse(String json, Type type) {
    return GSON.fromJson(json, type);
  }

  public static final <V> V parse(Reader reader, Class<V> type) {
    return GSON.fromJson(reader, type);
  }

  public static final <V> V parse(Reader reader, Type type) {
    return GSON.fromJson(reader, type);
  }
}

注册Record序列化适配器到GsonBuilder中:
builder.registerTypeAdapter(Record.class, new RecordAdapter())
注册Model序列化适配器到GsonBuilder中,这样所有继承Model的对象都会使用该适配器处理Gson
builder.registerTypeHierarchyAdapter(Model.class, new ModelAdapter());



加载中
0
JFinal
JFinal
感谢分享,顶一个先 
0
Jacky_D_H
Jacky_D_H

请问:

转为HashMap时,Gson默认把int转成了double, 这个怎样解决?

@JFinal


JFinal
JFinal
各种 json 转换工具对于 json 的具体类型转成 java 类型有自己的规则,例如 Gson 默认把长度达到某值的 int 转成了 double,建议转换时类型的转换根据 com.jfinal.plugin.activerecord.Table 中的映射来
返回顶部
顶部