简体   繁体   中英

Deserializing json as List<Object>

I have json:

"taxLevels": [{
        "code": "VAT",
        "percentage": 19.0
    }
]

This is truly List<TTaxLevel>

I have Model.class :

public class Model{

    private final List<TTaxLevel> taxLevels;
}

And TTaxLevel.class :

@NoArgsConstructor
public class TTaxLevel {

    private String code;
    private Double percentage;
}

But I receive error here:

[Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.String,java.lang.String> out of START_ARRAY token at [Source: (PushbackInputStream); line: 36, column: 19] (through reference chain: ...Model["taxLevels"])]]

Can I force somehow jackson to expect type here ArrayList instead of Map ? This is an issue.

This is deserialization code:

 Model model =  new ObjectMapper().readValue(content, Model .class);  

Please add getter/setter methods to you classes and provide no-arg constructor. Also you json is not completely valid, it should be:

{
  "taxLevels": [
    {
      "code": "VAT",
      "percentage": 19.0
    }
  ]
}

I trided putting it inside resource folder, fetch and then response to a sample request. Here is the sample code:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class Model {
    private List<TTaxLevel> taxLevels;
}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
class TTaxLevel {
    private String code;
    private Double percentage;
}

@RequestMapping("tax-level")
@RestController
class SampleRequestBody {
    private final ObjectMapper objectMapper;

    SampleRequestBody(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostMapping
    public Map<String, Model> taxLevel(@RequestBody Model model) throws JsonProcessingException {
        final Map<String, Model> response = new HashMap<>(1);
        response.put("data",  model);
        return response;
    }

    @GetMapping
    public Model getTaxLevel() throws IOException {
        InputStream inputStream = new ClassPathResource("tax-level.json").getInputStream();
        return objectMapper.readValue(inputStream, Model.class);
    }
}

So there are two issues:

  1. You need to provide getters and setters for your classes since the fields are all private;
  2. You need to change the Json to include "{" at the beginning and "}" at the end.
    {
        "taxLevels": [{
                "code": "VAT",
                "percentage": 19.0
            }
        ]
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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