杰克逊:如果房产丢失了怎么办?

2022-08-31 13:19:34

如果我使用对构造函数参数进行注释,但 Json 未指定该属性,会发生什么情况。构造函数获得什么值?@JsonProperty

如何区分具有空值的属性与 JSON 中不存在的属性?


答案 1

总结了程序员BruceStaxMan的优秀答案:

  1. 构造函数引用的缺失属性被分配一个由 Java 定义的缺省值。

  2. 可以使用 setter 方法来区分隐式或显式设置的属性。仅对具有显式值的属性调用 Setter 方法。Setter 方法可以跟踪属性是否使用布尔标志显式设置(例如 )。isValueSet


答案 2

如果我使用@JsonProperty注释构造函数参数,但 Json 未指定该属性,会发生什么情况。构造函数获得什么值?

对于这样的问题,我喜欢只写一个示例程序,看看会发生什么。

下面是这样一个示例程序。

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();

    // {"name":"Fred","id":42}
    String jsonInput1 = "{\"name\":\"Fred\",\"id\":42}";
    Bar bar1 = mapper.readValue(jsonInput1, Bar.class);
    System.out.println(bar1);
    // output: 
    // Bar: name=Fred, id=42

    // {"name":"James"}
    String jsonInput2 = "{\"name\":\"James\"}";
    Bar bar2 = mapper.readValue(jsonInput2, Bar.class);
    System.out.println(bar2);
    // output:
    // Bar: name=James, id=0

    // {"id":7}
    String jsonInput3 = "{\"id\":7}";
    Bar bar3 = mapper.readValue(jsonInput3, Bar.class);
    System.out.println(bar3);
    // output:
    // Bar: name=null, id=7
  }
}

class Bar
{
  private String name = "BLANK";
  private int id = -1;

  Bar(@JsonProperty("name") String n, @JsonProperty("id") int i)
  {
    name = n;
    id = i;
  }

  @Override
  public String toString()
  {
    return String.format("Bar: name=%s, id=%d", name, id);
  }
}

结果是构造函数被授予数据类型的默认值。

如何区分具有空值的属性与 JSON 中不存在的属性?

一种简单的方法是在反序列化处理后检查默认值,因为如果元素存在于 JSON 中但具有 null 值,则 null 值将用于替换给定相应 Java 字段的任何默认值。例如:

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFooToo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

    // {"name":null,"id":99}
    String jsonInput1 = "{\"name\":null,\"id\":99}";
    BarToo barToo1 = mapper.readValue(jsonInput1, BarToo.class);
    System.out.println(barToo1);
    // output:
    // BarToo: name=null, id=99

    // {"id":99}
    String jsonInput2 = "{\"id\":99}";
    BarToo barToo2 = mapper.readValue(jsonInput2, BarToo.class);
    System.out.println(barToo2);
    // output:
    // BarToo: name=BLANK, id=99

    // Interrogate barToo1 and barToo2 for 
    // the current value of the name field.
    // If it's null, then it was null in the JSON.
    // If it's BLANK, then it was missing in the JSON.
  }
}

class BarToo
{
  String name = "BLANK";
  int id = -1;

  @Override
  public String toString()
  {
    return String.format("BarToo: name=%s, id=%d", name, id);
  }
}

另一种方法是实现一个自定义反序列化程序,用于检查所需的 JSON 元素。另一种方法是在 http://jira.codehaus.org/browse/JACKSON


推荐