简体   繁体   中英

How to get the values stored in the class fields marked with @JsonProperty

I'm working on a project in struts2 using the json-plugin: I have a BaseAction that extends ActionSupport and declares some common fields marked with the @JsonProperty annotation.

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();
}

Every action in this framework extends the BaseAction and declares some specific fields marked as @JsonProperty.

public class SpecificAction extends BaseAction {
    @JsonProperty
    private String specificField1;
    @JsonProperty
    private String specificField2;

    public void executeAction() {
        //things
    }
}

I'm searching for a way to access, in the BaseAction, to all the values that are stored in all the @JsonProperty fields.

EDIT

I tried yesterday using

ObjectMapper mapper = new ObjectMapper(); 
mapper.writeValueAsString(this);

But it didn't work. Is this the right way?

I also tried using the reflection like the answer said, like 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);
                }

            }

But it returned me an exception that I'm not able to resolve:

IllegalArgumentException: Can not set net.sf.json.JSONObject field to java.lang.Object

The only way you can access properties from the superclass is through reflection.

In the BaseAction.execute() method, you can find out the actual object class, then iterate through all the attributes, checking if the attribute has the @JsonProperty annotation. If the annotation is found, you can get the name and attribute value.

I would recommend you to change your system design so you don't need to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM