gu.sql2java.json.FastjsonDeserializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sql2java-base Show documentation
Show all versions of sql2java-base Show documentation
sql2java common class package
package gu.sql2java.json;
import java.lang.reflect.Type;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer;
import com.google.common.collect.Lists;
import gu.sql2java.BaseBean;
import gu.sql2java.RowMetaData;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.MoreObjects.firstNonNull;
import static gu.sql2java.utils.CaseSupport.isSnakecase;
import static gu.sql2java.utils.CaseSupport.toCamelcase;
/**
* implementation of BaseBean class for
* FastJson {@code com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer},
* MAVEN dependencies:
*
* <dependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>${fastjson.version}</version>
* <scope>provided</scope>
* </dependency>
*
*
* @author guyadong
*
*/
public class FastjsonDeserializer extends JavaBeanDeserializer {
public FastjsonDeserializer(ParserConfig config, Class extends BaseBean> beanClass) {
super(config, checkNotNull(beanClass,"beanClass is null"));
}
public FastjsonDeserializer(Class extends BaseBean> beanClass) {
this(ParserConfig.global, beanClass);
}
@SuppressWarnings("unchecked")
@Override
public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
/** deserialze to JSONObject */
JSONObject json = (JSONObject)super.deserialze(parser, JSONObject.class, fieldName);
// replace key to camel-case if snake-case
for(String key:Lists.newArrayList(json.keySet()) ) {
if(isSnakecase(key)) {
String camelcase = toCamelcase(key);
if(!json.containsKey(camelcase)) {
json.put(camelcase, json.get(key));
json.remove(key);
}
}
}
/** convert Map to target type based BaseBean */
try {
return (T) createInstance(json, parser.getConfig());
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
/**
* define FASTJSON deserializer for all class derived from BaseBean using {@link ParserConfig#global}
*/
public static void install() {
install(ParserConfig.global);
}
/**
* define FASTJSON deserializer for all class derived from BaseBean
* @param config using {@link ParserConfig#global} instead of {@code null}
*/
public static void install(ParserConfig config) {
for(RowMetaData metaData:RowMetaData.allMetaDataList()){
ParserConfig.global.putDeserializer(
metaData.beanType,
new FastjsonDeserializer(firstNonNull(config,ParserConfig.global),metaData.beanType));
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy