Lavanya
Lavanya

Reputation: 33

How to Map data from JSON Array of Objects to My List

I am unable to unable to Map to the data .

I am sending the following JSON to map to my List Object

[{
    "Student": {
        "name": "Ram"
    },
    "Address": {
        "text": "6666 SE 3301"

    }
}]

This is Student class

@Data
public class Student {

        private String name;

}

This is Address class

@Data
public class Address {

    private String text;

}

This is AllDetails class

@Data
public class AllDetails {

    private Student student;
    private Address text;
}

This is the way i am accepting data

@PostMapping(value = AllDetails)
    public @ResponseBody String maptoObj(@RequestBody List<AllDetails> details) throws Exception {


        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        List<AllDetails> allDet = objectMapper.readValue(details,  AllDetails[].class);

        return "";
    }

Upvotes: 0

Views: 390

Answers (2)

Deepak
Deepak

Reputation: 181

Something along these lines

...
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
List<AllDetails> allDet = objectMapper.readValue(details, new TypeReference<>() {
        });
...



@Data
class AllDetails {
    @JsonAlias("Student")
    private Student student;
    @JsonAlias("Address")
    private Address address;

}

@Data
class Student {

    private String name;
}

@Data
class Address {

    private String text;

}

Upvotes: 0

pvpkiran
pvpkiran

Reputation: 27048

Try this. This should work.

public class AllDetails {
    @JsonProperty("Student")
    private Student student;
    @JsonProperty("Address")
    private Address address;
}

Variable name you are using: student and address.
But in Json it is Student and Address.

use @JsonProperty to tell jackson what is the variable name in json it should look for

Upvotes: 2

Related Questions