如何通过Jersey(JAX-RS)实现Java REST API接收Postman多JSON数据
Hey, I see exactly where the issue is! You’re using @RequestBody—that’s a Spring MVC annotation, not something Jersey (JAX-RS) recognizes. That’s why your getPatientDetails method isn’t being triggered at all. Let’s fix this step by step to get your JSON array working properly.
Step 1: Remove the incorrect annotation and adjust your API method
First, get rid of the @RequestBody entirely. Jersey handles JSON deserialization for collections natively, but we need to structure the method correctly. Here’s the corrected code:
@Path("patientDetail") @POST @Consumes(MediaType.APPLICATION_JSON) public String getPatientDetails(List<Patient> patients) { for (Patient p : patients) { System.out.println(p.getFirstName()); System.out.println(p.getLastName()); } return "ok"; }
Step 2: Add Jackson JSON provider dependency
Jersey doesn’t come with full support for JSON array deserialization out of the box. You’ll need to add the Jackson JAX-RS provider to your project to convert JSON arrays to Java Lists seamlessly.
If you’re using Maven, add this to your pom.xml:
<dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.15.2</version> <!-- Use the latest stable version available --> </dependency>
For Gradle users, add this to your build script:
implementation 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.15.2'
Step 3: Register the Jackson provider (if required)
Some Jersey setups need manual registration of the Jackson provider. If you have a Jersey application config class, update it to include:
public class YourJerseyAppConfig extends ResourceConfig { public YourJerseyAppConfig() { // Register Jackson's JSON handling provider register(JacksonJsonProvider.class); // Register your patient resource class here register(YourPatientResource.class); } }
Step 4: Test with Postman
Double-check your Postman request setup:
- Set the method to
POST - Add a
Content-Typeheader with valueapplication/json - Paste your JSON array into the request body:
[{"firstName":"riya","lastName":"soni"},{"firstName":"shreya","lastName":"patel"}]
Backup solution: Manual deserialization (for type erasure issues)
If you hit problems with generic type erasure, you can use Jackson’s ObjectMapper to parse the JSON directly:
@Path("patientDetail") @POST @Consumes(MediaType.APPLICATION_JSON) public String getPatientDetails(String jsonPayload) { ObjectMapper objectMapper = new ObjectMapper(); try { List<Patient> patients = objectMapper.readValue( jsonPayload, new TypeReference<List<Patient>>() {} ); for (Patient p : patients) { System.out.println(p.getFirstName()); System.out.println(p.getLastName()); } } catch (JsonProcessingException e) { e.printStackTrace(); return "error parsing JSON"; } return "ok"; }
内容的提问来源于stack exchange,提问作者Riya Soni

