Home > Mobile >  Jackson cannot map JSON to Object in Java
Jackson cannot map JSON to Object in Java

Time:08-21

I am trying to map the following JSON string to a pojo class:

{
    "Data": {
        "brand": "Porsche",
        "model": 2020,
        "color": "gray"
    },
    "Section": {
        "location": "UK",
        "service": "London"
    },
    // other elements 
}

I am only interested in 2 fields (brand, model) in the Data part and want to map these 2 fields to the following model:

Data:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {

    @JsonProperty("brand")
    private String brand;

    @JsonProperty("model")
    private int model;
}

However, although jsonString has a valid JSON, the fields in Data are null or empty.

// jsonString is a valid JSON string read from a REST API via WebClient
String jsonString = request.block(); 
ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(value, Data.class);

So, what is missing? Is there any problem regarding to pojo fields or annotations in it? Could you help me pls?

CodePudding user response:

You have not specified any class to catch the response. You have only created 1 model to catch the Data object. You can do it like this,

i) Create a class to catch the JSON,

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Payload {

    @JsonProperty("Data")
    private Data data;

  
}

You have to first catch the JSON using the Payload class and then parse it accordingly,

String jsonString = request.block(); 
ObjectMapper mapper = new ObjectMapper();
Payload payload = mapper.readValue(jsonString, Payload.class);
Data data = payload.getData();

ii) Without any extra class,

String payloadString = "{\n"  
                "    \"Data\": {\n"  
                "        \"brand\": \"Porsche\",\n"  
                "        \"model\": 2020,\n"  
                "        \"color\": \"gray\"\n"  
                "    },\n"  
                "    \"Section\": {\n"  
                "        \"location\": \"UK\",\n"  
                "        \"service\": \"London\"\n"  
                "    }\n"  
                "}";
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> objectMap = objectMapper.readValue(payloadString, HashMap.class);
        String dataString = objectMapper.writeValueAsString(objectMap.get("Data"));
        Data data = objectMapper.readValue(dataString, Data.class);
        System.out.println(data);
  • Related