简体   繁体   English

如何将 JSON 中 Java 对象的实例类型发送到 Java Spring-Server Post 请求?

[英]How to send the instance type of a Java Object in JSON to Java Spring-Server Post request?

I have a baseclass and three extending classes.我有一个基类和三个扩展类。 For example:例如:

BaseClass:基类:

public BaseClass {
 int id;
} 
public SubClass extends BaseClass {
 int sub1;
}
public SubClass2 extends BaseClass {
 int sub2;
}

Now i want to send a json file to my spring server and the server must check if it is a SubClass-type or a SubClass2-type现在我想向我的 spring 服务器发送一个 json 文件,服务器必须检查它是 SubClass 类型还是 SubClass2 类型


    @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> create(@RequestBody List<BaseClass> entry);

sending JSON:发送 JSON:

{
    "id": 1,
    "sub1": 1
},
{
    "id": 2,
    "sub2": 2
}

I except a List of BaseClasses but try to cast them in the specific subclass.我除了一个 BaseClass 列表,但尝试将它们转换为特定的子类。 How can i do this?我怎样才能做到这一点? Following did not work.以下没有奏效。

if (abc instanceof SubClass) {
                log.info("abc is instance of SubClass");
} else if (abc instanceof SubClass2) {
                log.info("abc is instance of SubClass2");
} 

If you will accept BaseClass Spring will map your json to be compliant with only BaseClass ignoring all the other fields.如果您接受BaseClass Spring 将映射您的 json 以仅与BaseClass兼容,而忽略所有其他字段。 So your check for subclasses will not work at all.因此,您对子类的检查根本不起作用。

The simplest solution is to accept data as plain text and after that manually try to map it to your models using GSON or something similar like this最简单的解决方案是接受纯文本数据,然后手动尝试使用 GSON 或类似的东西将其映射到您的模型

new Gson().fromJson("{
    "id": 1,
    "sub1": 1
}", SubClass.class);

But it is a bad way to handle this.但这是一种糟糕的处理方式。 Your approach need to be changed architecturally.您的方法需要在架构上进行更改。 The simplest way to do it is to introduce data field to you model like this最简单的方法是像这样将data字段引入您的模型

{
    "id": 1,
    "data": {
         "key": "sub1",
         "value": 1
     },
},
public Data {
 String key;
 int value
} 

public BaseClass {
 int id;
 Data data;
} 

this way you will be able to check这样你就可以检查

if (abc.data.key.equals("sub1")) {
                log.info("abc is sub1");
} else if (abc.data.key.equals("sub1")) {
                log.info("abc is sub2");
} 

This will require a bit more complex further implementation, but it will work.这将需要更复杂的进一步实现,但它会起作用。

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM