当我们使用gson将java bean转换为json字符串时,我想扩展Gson库以启用字段级自定义转换。
类似的东西:
@Convert(expression="if(#value == '1') then 'enabled' else 'disabled'")
private String roleStatus;
如何在java中实现这样的表达式解释器?春天表达能做到吗?
答案 0 :(得分:4)
例如你的json如下:
{
"roleStatus" : "3"
"role" : "guest"
}
<强> 1。首先,您需要将Converter注释字段级别创建为
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Convertor {
String expression();
}
<强> 2。然后使用JsonDeserializer
解析gson自定义级别反序列化import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import org.mvel2.MVEL;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class RoleStatusDeserializer implements JsonDeserializer<RoleStatus> {
@Override
public RoleStatus deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
// get roleStatus from jsonObject and populate new roleStatus object
final RoleStatus roleStatus = new RoleStatus(jsonObject.get("roleStatus").getAsString());
final String expression = getFiledAnnotationValue();
// Evaluate expression via Mvel.
final String result = (String) MVEL.eval(expression, roleStatus);
// update statusRole
roleStatus.setRoleStatus(result);
return roleStatus;
}
/**
* reading Filed level annotation via java reflection
* @return annoation value
*/
private String getFiledAnnotationValue() {
String expression = null;
for (Field field : RoleStatus.class.getDeclaredFields()) {
final Annotation annotation = field.getAnnotation(Convertor.class);
if (annotation instanceof Convertor) {
field.setAccessible(true);
Convertor convertorAnnotation = (Convertor) annotation;
expression = convertorAnnotation.expression();
field.setAccessible(false);
}
}
return expression;
}
}
第3。使用java反射在RoleStatusDeserializer #deserialize()中获取注释值(表达式)
4.一旦获得注释表达式值,则必须使用MVEL
评估表达式值MVEL是基于Java的应用程序的强大表达式语言,大多数开源应用程序都使用mvel,例如spring,warp-persist等。 您可以从Mvel site
下载Mvel最新版本<强> 5。最后将其解析为
JsonReader reader = new JsonReader(new FileReader("your_path"));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(RoleStatus.class,new RoleStatusDeserializer());
Gson gson = gsonBuilder.create();
RoleStatus roleStatus = gson.fromJson(reader, RoleStatus.class);