Forum Discussion

KdJ's avatar
KdJ
Regular Visitor
6 months ago

Java client code generated from anyOf using array and object types is not usable

Hi,

 

I generated a Java client using https://editor-next.swagger.io/ for a REST API that we want to consume. The schemas for this API have various elements with a definition like this:

  ...
  "components": {
    ...
    "schemas": {
      "report": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          ...
          "analysis": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/analysisType"
              },
              {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/analysisType"
                },
                "description": "maximum 4"
              }
            ]
          }
        }
      },
      "analysisType": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string"
          },
          "codeDescription": {
            "type": "string"
          },
          "percentage": {
            "type": "integer"
          },
          "sequenceNumber": {
            "type": "integer"
          }
        },
        "required": [
          "code",
          "percentage",
          "sequenceNumber"
        ]
      }
...

 

So it's basically a field that consists of either a single element of type AnalysisType, or an array of type AnalysisType.

 

The Java code generated for this is useless. An interface named AnyOfanalysis is generated without any methods, and a class named AnalysisType implementing this interface is generated which is basically the single element case. A class named Report is also generated which has a field analysis of type AnyOfanalysis.

 

Any ideas on this? Should I report this as an issue?

 

P.S. Jackson can deal with this by configuring the ObjectMapper:

 

    test
    public void givenJsonElement_whenDeserializingAsList_thenCorrect()
            throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        String jsonElement = mapper.writeValueAsString(new AnalysisType().code("foo").percentage(20).sequenceNumber(1));

        List<AnalysisType> asList = mapper.readValue(jsonElement, new TypeReference<List<AnalysisType>>() {
        });
        assertEquals(1, asList.size());
        assertEquals(AnalysisType.class, asList.get(0).getClass());
    }

 

If the generated code defines the field analysis of the class Report as List<AnalysisType> this would work out of the box.

No RepliesBe the first to reply