【问题标题】:How to remove null value Strings from Json while converting pojo to Json using Json.toJson() in play framework?如何在播放框架中使用 Json.toJson() 将 pojo 转换为 Json 时从 Json 中删除空值字符串?
【发布时间】:2016-05-21 06:02:06
【问题描述】:

当我们从pojo转换为json时,我们如何获得没有空字符串的结果json?

 class Test{
        public String id;
        public String firstname;
        public String lastname;
        }

        Test test=new Test();
        test.id="1";
        test.firstname="John";

当我们将 test 转换为 json 时:

Json.tojson(test); // using play.libs.Json

结果:

{
    "id":"1",
    "firstname":"John",
    "lastname":null
    }

预期结果:

{
    "id":"1",
    "firstname":"John"
    }

有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: java json playframework pojo


    【解决方案1】:

    您应该注释您的 POJO,例如:

    /**
     * Test class annotate to tell Jackson library to NOT include NULL values.
     */
    @JsonInclude(Include.NON_NULL)
    class Test {
        public String id;
        public String firstname;
        public String lastname;
    }
    

    【讨论】:

      【解决方案2】:

      要禁止使用 null 值序列化属性,您可以直接配置 ObjectMapper,或使用 @JsonInclude 注解:

       mapper.setSerializationInclusion(Include.NON_NULL);
      

      或:

       @JsonInclude(Include.NON_NULL)
       class Foo
       {
          String bar;
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        • 2015-11-16
        • 1970-01-01
        • 2017-05-20
        • 2018-01-11
        • 1970-01-01
        相关资源
        最近更新 更多