【问题标题】:How to get the values stored in the class fields marked with @JsonProperty如何获取存储在标有@JsonProperty 的类字段中的值
【发布时间】: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


【解决方案1】:

您可以从超类访问属性的唯一方法是通过反射。

在BaseAction.execute()方法中,可以找出实际的对象类,然后遍历所有属性,检查属性是否有@JsonProperty注解。如果找到注解,就可以得到名称和属性值。

我建议你改变你的系统设计,这样你就不需要这样做了。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多