我创建了反序列化的样例类和响应,但这是需要修复的同一个问题.响应可以是带对象的数组,也可以是just an Object. 需要动态反序列化

班级

public record  Main班级(
  //the response can either be array or not array
  @JsonProperty("Relation") List<Relation> relation
){

 
}


public record  Relation(
   String relation,
   String Id,
){

 
}

如果响应为数组Working,则反序列化

响应

{
 "Relation": [
          {
            "url": "https://sample.com",
            "Id": "77"
          }
        ]
        
}

当If响应不是数组时反序列化 This need to be fix

响应

{
 "Relation":{
            "url": "https://sample.com",
            "Id": "77"
          }
        
        
}

推荐答案

另一种 Select 是为该属性提供两个设置器.

public class RelationWrapper
   private String id;
   private List<Relation> relation;

   public void setRelation(Relation relation) {
      this.relation = relation == null ? null : List.of(relation);
   }

   public void setRelation(List<Relation> relation) {
      this.relation = relation;
   }

   public List<Relation> getRelation() {
      return relation;
   }
}

这也可以用两个构造函数来完成

public class RelationWrapper
   private final String id;
   private final List<Relation> relation;

   @ConstructorProperties({"id", "relation"})
   public RelationWrapper(String id, List<Relation> relation) {
      this.id = id;
      this.relation = relation;
   }

   @ConstructorProperties({"id", "relation"})
   public RelationWrapper(String id, Relation relation) {
      this.id = id;
      this.relation = relation == null ? null : List.of(relation);
   }

   // getters
}

Java相关问答推荐

javafx getHostServices(). showDocument()调出Chrome而不是默认浏览器(Linux)

工件部署期间出错[Tomcat 8.5.45]

编译多个.Java文件并运行一个依赖于用户参数的文件

带错误BER验证的itext8签名返回pdf

用户填充的数组列表永不结束循环

在添加AdMob时无法为Google Play构建应用程序包:JVM垃圾收集器崩溃和JVM内存耗尽

try 从REST API返回对象列表时出错

try 在Android Studio中的infoWindow中使用EditText(Java)

在VS代码中,如何启用Java Main函数的&Q;Run|DEBUG&Q;代码?

将ByteBuffer异步写入InputStream或Channel或类似对象

try 使用类来包含JSON响应

为什么StandardOpenOption.CREATE不能通过Ubuntu在中小企业上运行?

Android Studio模拟器没有互联网

如何使用jooq更新记录?

我无法在我的Spring Boot应用程序中导入CSV依赖项

如何在Spring Boot中为不同的部署环境管理多个.properties文件?

";home/runner/work/中没有文件...匹配到[**/pom.xml];Maven项目的构建过程中出现错误

如何使用命令行为Java应用程序生成烟雾测试用例

使用DynamoDB增强客户端时未更新属性

在对象列表上调用提取后,如何判断没有值为空?