【问题标题】:Display Zero Value in Json在 Json 中显示零值
【发布时间】:2017-11-21 23:05:54
【问题描述】:

我正在使用 Jersy 在应用程序中生成 Json。 产生Json的代码sn-p如下

    @GET    
    @Produces(MediaType.APPLICATION_JSON)
    @Path("sample")
    public List<test> displaySampleMessage(@PathParam("id") int id) 
    {
        System.out.println(id);
        List<test> sample1 = new ArrayList<>();

        test temp1 =    new test();
        temp1.setName("abc");   
        sample1.add(temp1);

        return sample1;
    }

测试是简单的java类,代码如下

package webServiceTester;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class test 
{
    private String name;
    private int age;

    public test()
    {

    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public test(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }   
}

然后,当我运行此 Web 服务时,我得到以下输出

我不想在这里得到age = 0,因为我没有设置对象的age 属性。 它的解决方案是什么。如果我设置了值,我希望出现年龄,否则它不应该出现..

【问题讨论】:

  • 没有人可以知道一个 int 的值为 0 是因为您设置了它,还是因为您没有设置它,因此它具有默认值。您将需要其他东西,例如 Integer(默认情况下为 null)来执行此操作。请尊重 Java 命名约定。类以大写字母开头。
  • 好的。我制作这个示例只是为了测试目的,这就是我不遵循约定的原因。
  • 感谢您的回答

标签: java web-services jersey jersey-2.0


【解决方案1】:

使用 Jaksonhere 你可以找到一个 带有 Jersey + Jackson 的 JSON 示例。 所以你可以使用@JsonSerialize注解来排除null或者空字段。

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)

但是,在 restful 应用程序中排除 null 或空字段并不是一个好习惯,因为它可能会导致客户端出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2010-10-26
    • 2021-02-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多