使用静止保证时,如果我发送邮政请求将数据提交给服务器,我该如何故意忽略JSON字符串中的某些属性?

发布于 2025-02-12 07:01:39 字数 887 浏览 0 评论 0原文

给定这个简单的类,代表A person 对象:

@Builder
public class Person {
         int age;
         String name;
    }

使用构建器创建一个 person 的实例,并使用REST保证将其发布到服务器上:

public class main {
     public static void main(String [] args){
          Person p1 = Person.builder().name("John").build();
          Person p2 = Person.builder().age(29).build();
          //CODE TO SEND POST REQUEST USING REST ASSURED
     }
}

据我了解,相应的JSON字符串服务器收到的看起来像这样的东西:

p1: { "name": "John", "age": 0 }
p2: { "name": null, "age": 29 }

我的问题是:我如何故意忽略类的某些属性? 可以说,我要发布的数据的终点要求该模式包含年龄或名称属性,但是为了测试目的,我想忽略年龄属性,以便收到的年龄属性看起来像这样:

p1: { "name": "John" }
p2: { "age": 29 }

我在想我在想我可以创建一个代表一个人的单独的类似类,但可以删除所讨论的属性。这似乎是错误的,效率低下。有更好的方法吗?还是在引擎盖下有某种事情会通过故意不可分化的属性,在邮政请求中遗留下来?感谢您的时间。

Given this simple class representing a Person object:

@Builder
public class Person {
         int age;
         String name;
    }

Using builder to create an instance of Person and posting it to a server using Rest Assured:

public class main {
     public static void main(String [] args){
          Person p1 = Person.builder().name("John").build();
          Person p2 = Person.builder().age(29).build();
          //CODE TO SEND POST REQUEST USING REST ASSURED
     }
}

As I understand it, the corresponding json string being received by the server would look something like this:

p1: { "name": "John", "age": 0 }
p2: { "name": null, "age": 29 }

My question is: How can I intentionally leave out certain attributes of a class?
Lets say that the endpoint which I am posting this data to requires that the schema contains an age or name attribute, but for testing purposes, I want to leave out the age attribute so that what is received looks something like this:

p1: { "name": "John" }
p2: { "age": 29 }

I am thinking I could create a separate, similar class representing a person, but removing the attribute in question. This just seems wrong and inefficient. Is there a better way? Or is there some sort of stuff going on under the hood that by intentionally uninitializing an attribute, its left out in the post request? Thanks for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请别遗忘我 2025-02-19 07:01:39

这取决于您如何发送人员类,但是您可以选择使用null值通过@jsoninclude(include.non_null)进行过滤值,或具有不同的映射器根据用例配置。

此答案描述了一种方法杰克逊或格森。

It depends on how you are sending the Person class, but you could opt to filter out the null values by using @JsonInclude(Include.NON_NULL), or have a different mapper configured depending on your use case.

This answer describes a way how to do this with either Jackson or Gson.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文