问题

这豆'州':

public class State {

    private boolean isSet;

    @JsonProperty("isSet")
    public boolean isSet() {
        return isSet;
    }

    @JsonProperty("isSet")
    public void setSet(boolean isSet) {
        this.isSet = isSet;
    }

}

使用ajax'success'回调通过线路发送:

success : function(response) {  
            if(response.State.isSet){   
                alert('success called successfully)
            }

这里需要注释@JsonProperty吗?使用它有什么好处?我想我可以删除这个注释而不会产生任何副作用。

在2333437408上阅读关于这个注释的内容我不知道何时需要使用它?


#1 热门回答(150 赞)

这是一个很好的例子。我用它来重命名变量,因为JSON来自a.Net环境,其中属性以大写字母开头。

public class Parameter {
  @JsonProperty("Name")
  public String name;
  @JsonProperty("Value")
  public String value; 
}

这正确地解析到JSON:

"Parameter":{
  "Name":"Parameter-Name",
  "Value":"Parameter-Value"
}

#2 热门回答(27 赞)

我认为OldCurmudgeon和StaxMan都是正确的,但这里有一句简单的例子给你答案。

@JsonProperty(name)告诉Jackson ObjectMapper将JSON属性名称映射到带注释的Java字段的名称。

//example of json that is submitted 
"Car":{
  "Type":"Ferrari",
}

//where it gets mapped 
public static class Car {
  @JsonProperty("Type")
  public String type;
 }

#3 热门回答(25 赞)

以及它现在的价值... JsonProperty还用于为变量指定getter和setter方法,除了通常的序列化和反序列化。例如,假设你有这样的有效负载:

{
  "check": true
}

和反序列化器类:

public class Check {

  @JsonProperty("check")    // It is needed else Jackson will look got getCheck method and will fail
  private Boolean check;

  public Boolean isCheck() {
     return check;
  }
}

然后在这种情况下需要JsonProperty注释。但是如果你在课堂上也有一个方法

public class Check {

  //@JsonProperty("check")    Not needed anymore
  private Boolean check;

  public Boolean getCheck() {
     return check;
  }
}

另请查看此文档:http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html


原文链接