2017-01-30 75 views
0

我正在使用Swagger來生成我的DTO。 我有一個InputField和一個繼承Field類的TextareaField DTO。Swagger Spring polymorph DTO

我YAML有如下定義:

definitions: 
    field: 
    discriminator: fieldType 
    required: 
     - name 
     - fieldType # required for inheritance to work 
    properties: 
     name: 
     type: string 
     fieldType: 
     type: string 
    inputField: 
    allOf: 
     - $ref: '#/definitions/field' # All properties of a Field 
     - properties: # extra properties only for fields 
      placeholder: 
      type: string 
    textareaField: 
    allOf: 
     - $ref: '#/definitions/field' # All properties of a Field 
     - properties: # extra properties only for fields 
      placeholder: 
      type: string 
    form: 
    type: object 
    required: 
     - name 
    properties: 
     name: 
     type: string 
     fields: 
     type: array 
     items: 
      $ref: '#/definitions/field' 

然後在我的春天終點,我有以下REST控制器:

@Override 
public ResponseEntity<Void> addForm(@ApiParam(value = "form object to add to the store", required = true) @RequestBody Form form) { 

    if(form.getFields().isEmpty()){ 
     return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); 
    } 

    ch.test.form.database.model.Form formModel = new ch.test.form.database.model.Form(); 
    formModel.setName(form.getName()); 

    for(Field field: form.getFields()){ 
     System.out.println(field); 
     switch(field.getFieldType()){ 
      case "InputField": 
       formModel.addField(new InputField(field.getName(), ((ch.test.form.api.dto.InputField)field).getPlaceholder())); 
       break; 
      case "TextareaField": 
       formModel.addField(new TextareaField(field.getName(), ((ch.test.form.api.dto.TextareaField)field).getPlaceholder())); 
       break; 
     } 
    } 

    formModel.setUser(user); 

    try{ 
     formRepository.save(formModel); 
     HttpHeaders responseHeaders = new HttpHeaders(); 
     responseHeaders.set("location", "/pointScales/" + formModel.getId()); 
     return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).build(); 
    } catch (DataIntegrityViolationException e){ 
     System.out.println(e.getMessage()); 
     System.out.println(e.getClass()); 
     return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build(); 
    } 
} 

創建與新inputfield當我得到這個異常java.lang.ClassCastException: ch.test.form.api.dto.Field cannot be cast to ch.test.form.api.dto.InputField以下json:

{ 
"fields": [ 
    { 
     "fieldType": "InputField", 
     "name": "string", 
     "placeholder": "test" 
    } 
    ], 
    "name": "string" 
} 

我在做什麼wr翁?創建dtos時是否缺少註釋swagger?

回答

0

我刪除了swagger代碼生成,所以我可以自己配置DTO並添加@JsonTypeInfo註釋。