【问题标题】:java model mock response jsonjava模型模拟响应json
【发布时间】:2022-01-15 08:47:07
【问题描述】:

我正在创建一个调用外部服务的 Rest 服务。 我有这个问题:我调用的外部服务根据成功或失败的情况以两种方式响应。这是json:

json{
    "result": "001",
    "status": "Success",
    "response": {
        "codiceCase": "CAS-46759-Q8P7X3",
        "guidCase": "88458d32-dd42-ec11-8c62-0022489d2f61"}
} 
OR 
{
    "result": "002",
    "status": "Failed",
    "errorManagement": {
        "errorCode": "E02",
        "errorDescription": "field not value in body"
    }
}

我创建了 3 个简单的类:

  1. class XXX...私有字符串结果,状态; .... 获取器和设置器
  2. 类响应...私有字符串 codeceCase, guidCase; ... getter & setter
  3. 类 ErrorManagement...private String errorCode, errorDescription;... getter & setter 但是当我用我的模拟填充时,json 总是由我不关心的类字段组成,例如:
{
    "result": "001",
    "status": "Success",
    "response": {
        "codiceCase": "CAS-46759-Q8P7X3",
        "guidCase": "88458d32-dd42-ec11-8c62-0022489d2f61"    },
        {
***"errorMessage"**: null}
}

我怎样才能在我的模拟中只获得 3 个类中的 2 个作为 json 返回? 感谢您的帮助。

【问题讨论】:

  • 你用的是什么 json 库?杰克逊?
  • 嗨,dpr。 json 响应来自外部服务。
  • @Sergio,不回答@dpr 问题。您使用哪个库从/到 Java 对象序列化/反序列化 JSON?杰克逊?格森?
  • 对不起@dpr,@João Dias。我不明白。我使用 spring-boot-starter-web 调用的默认 Spring Boot 库,它应该是 Jackson。

标签: java json spring spring-boot


【解决方案1】:

我想您正在使用 Jackson 来反序列化 JSON,因为这是 - 我认为 - spring 的默认设置。

使用 Jackson,您可以注释模型类以在 JSON 字符串表示中省略 null 值:

@JsonInclude(Include.NON_NULL)
public class Model { … }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多