【发布时间】:2016-08-17 15:59:49
【问题描述】:
我正在使用 json-plugin 在 struts2 中开发一个项目:我有一个 BaseAction,它扩展了 ActionSupport 并声明了一些用 @JsonProperty 注释标记的公共字段。
public abstract class BaseAction extends ActionSupport {
@JsonProperty
private String commonField1;
@JsonProperty
private String commonField2;
public String execute() {
executeAction();
//some things to get the values in the JsonProperties
}
public abstract void executeAction();
}
此框架中的每个操作都扩展了 BaseAction 并声明了一些标记为 @JsonProperty 的特定字段。
public class SpecificAction extends BaseAction {
@JsonProperty
private String specificField1;
@JsonProperty
private String specificField2;
public void executeAction() {
//things
}
}
我正在寻找一种在 BaseAction 中访问存储在所有 @JsonProperty 字段中的所有值的方法。
编辑
我昨天试过用
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(this);
但它没有用。这是正确的方法吗?
我也尝试过像答案所说的那样使用反射,如下所示:
Field[] fields = this.getClass().getDeclaredFields();
Map<String, Object> jsonProperties = new HashMap<String, Object>();
for (Field field : fields) {
logger.debug(methodName, "Field " + field.getName());
field.setAccessible(true);
try {
if(field.isAnnotationPresent(JsonProperty.class)) {
Object obj = new Object();
logger.debug(methodName, "Field: " + field.getName());
jsonProperties.put(field.getName(), field.get(obj));
}
} catch(Exception e) {
logger.error(methodName, "Errore", e);
}
}
但它返回了一个我无法解决的异常:
IllegalArgumentException:无法将 net.sf.json.JSONObject 字段设置为 java.lang.Object
【问题讨论】:
-
杰克逊可以访问这些属性。
标签: java json struts2 subclass