0

I have a Json string like below

{
  "EngineData": [
    {
      "make": "Toyota",
      "transmission": "Manual",
      "fuel": "Petrol"
    },
    {
      "make": "GMC",
      "transmission": "Auto",
      "fuel": "Petrol"
    },
    {
      "make": "Honda",
      "transmission": "Manual",
      "fuel": "Petrol"
    }
  ]
}

I have the POJO defined like below

@JsonIgnoreProperties(ignoreUnknown = true)
public class EngineData implements Serializable {
    @JsonProperty("make")
    private String make;
    @JsonProperty("transmission")
    private String transmission;
    @JsonProperty("fuel")
    private String fuel;

    //getters and setters
    
}

I wanted to read it to List<EngineData>

I wrote the following but it doesn't read the String to a EngineData list

List<EngineData> engineDataList =null;
ObjectMapper mapper = new ObjectMapper();
engineDataList = mapper.readValue(myJsonString, new TypeReference<List<EngineData>>() {
            });

Not sure whats wrong in this

deadshot
  • 8,881
  • 4
  • 20
  • 39
Jeeppp
  • 1,553
  • 3
  • 17
  • 39

2 Answers2

2

Your JSON corresponds to an object such as :

class CustomObject {
   List<EngineData> EngineData;
   //...
}

It will work with bellow JSON :

[
    {
      "make": "Toyota",
      "transmission": "Manual",
      "fuel": "Petrol"
    },
    {
      "make": "GMC",
      "transmission": "Auto",
      "fuel": "Petrol"
    },
    {
      "make": "Honda",
      "transmission": "Manual",
      "fuel": "Petrol"
    }
  ]

If you're forced to use this JSON I think you will need to write a custom deserializer. cf. https://www.baeldung.com/jackson-deserialization

Logan Wlv
  • 3,274
  • 5
  • 32
  • 54
0

Object can not be mapped to a list,

Refer this for mapping the given json:

public class EngineDataList {
   @JsonProperty("EngineData")
   List<EngineData> EngineData;
}

EngineDataList engineDataList =null;
ObjectMapper mapper = new ObjectMapper();
engineDataList = mapper.readValue(myJsonString, new TypeReference<EngineDataList>() {});
atul
  • 56
  • 9