0

We are developing a Java EE project and need to expose a RESTFul web-service that uses JSON. Unfortunately, I cannot bind a JSON parameter to Java object in a Http-POST request. Could you help me?

The service class:

@Path("claimserviceNew")
public class SlsiRestServicesNew {

@POST
@Consumes({"application/xml", "application/json"})
@Produces(MediaType.APPLICATION_JSON)
public String registerClaimWithPaymentNew( Mandant mandant, Vertrag vertrag){

    return mandant.getCode() + " new ";
}

}

The Mandant class:

@XmlRootElement(name="mandant")
@XmlAccessorType(XmlAccessType.FIELD)
public class Mandant {


    @XmlAttribute(required=true)
    private String code;


    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

}

The Vertrag class:

@XmlRootElement(name="vertrag")
@XmlAccessorType(XmlAccessType.FIELD)
public class Vertrag {

    @XmlAttribute(required=true)
    private String polizzenNummer;

    public String getPolizzenNummer() {
        return polizzenNummer;
    }

    public void setPolizzenNummer(String polizzenNummer) {
        this.polizzenNummer = polizzenNummer;
    }

}

My both JSON parameters in my HTTP Post Request:

{   { 
        "code": "SLV"
    },

     { 
        "polizzenNummer": "1234"
     }

}

Exception on the server:

Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
 at [Source: org.apache.catalina.connector.CoyoteInputStream@cce46; line: 1, column: 6]
    at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1433) [jackson-core-asl-1.9.9-redhat-2.jar:1.9.9-redhat-2]
Alex Mi
  • 1,409
  • 2
  • 21
  • 35

3 Answers3

1

As I understand from your description & JSON, I think you want to pass the both objects encapsulated in one. To do so you have to specify the inner objects/variables name. Like below- { "mandant" : { "code": "SLV" },

"vertrag" : { "polizzenNummer": "1234" }

}

nIKHIL
  • 108
  • 2
  • 8
1

Your REST method can receive only ONE object via Json Binding. In this case, you probably want to create one object that encapsulates both:

public class MyInput {
   private Vertrag vertrag;
   private Mandant mandant;
   // .. getters and setters
}

Then you receive this in your REST method:

@POST
@Consumes({"application/xml", "application/json"})
@Produces(MediaType.APPLICATION_JSON)
public String registerClaimWithPaymentNew(MyInput input){

    return input.getMandant().getCode() + " new ";
}
Guilherme Mussi
  • 956
  • 7
  • 14
0

You should name your two fields in your json structure like this:

{
    "field1": { "code": "SLV" },
    "field2": { "polizzenNummer": "1234" }
}

Or even better :

{
    "code": "SLV",
    "polizzenNummer": "1234"
}