0
votes

I'm stuck trying to send JSON data to by Struts2 REST server using the struts2-rest-plugin.

It works with XML, but I can't seem to figure out the right JSON format to send it in.

Anybody has any experience with this?

Thanks, Shaun

Update:

Sorry I wasn't clear. The problem is that Struts2 doesn't seem to be mapping the JSON data I send in to my model in the controller.

Here's the code:

Controller:

public class ClientfeatureController extends ControllerParent implements ModelDriven<Object> {
    private ClientFeatureService clientFeatureService;

    private ClientFeature clientFeature = new ClientFeature();
    private List<ClientFeature> clientFeatureList;

    //Client ID
    private String id;

    public ClientfeatureController() {
        super(ClientfeatureController.class);
    }

    @Override
    public Object getModel() {
        return (clientFeatureList != null ? clientFeatureList : clientFeature);
    }

    /**
     * @return clientFeatureList through Struts2 model-driven design
     */
    public HttpHeaders show() {
        //logic to return all client features here. this works fine..

        //todo: add ETag and lastModified information for client caching purposes
        return new DefaultHttpHeaders("show").disableCaching();
    }

    // PUT request
    public String update() {
        logger.info("client id: " + clientFeature.getClientId());
        logger.info("clientFeature updated: " + clientFeature.getFeature().getDescription());

        return "update";
    }

    public HttpHeaders create() {
        logger.info("client id: " + clientFeature.getClientId());
        logger.info("feature description: " + clientFeature.getFeature().getDescription());
        return new DefaultHttpHeaders("create");
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setClientFeatureService(ClientFeatureService clientFeatureService) {
        this.clientFeatureService = clientFeatureService;
    }

    public List<ClientFeature> getClientFeatureList() {
        return clientFeatureList;
    }

    public void setClientFeatureList(List<ClientFeature> clientFeatureList) {
        this.clientFeatureList = clientFeatureList;
    }

    public ClientFeature getClientFeature() {
        return clientFeature;
    }

    public void setClientFeature(ClientFeature clientFeature) {
        this.clientFeature = clientFeature;
    }
}

This is the URL I'm making the request to:

..http://localhost:8080/coreserviceswrapper/clientfeature.json

-Method: POST or PUT (tried both, POST maps to create() and PUT maps to update()) -Header: Content-Type: application/json

Payload:

{"clientFeature":{
        "feature": {
            "id": 2,
            "enabled": true,
            "description": "description1",
            "type": "type1"
        },
        "countries": ["SG"],
        "clientId": 10}
}

And the output in the Struts2 logs when I make the request:

1356436 [http-bio-8080-exec-5] WARN  net.sf.json.JSONObject  - Tried to assign property clientFeature:java.lang.Object to bean of class com.foo.bar.entity.ClientFeature
1359043 [http-bio-8080-exec-5] INFO  com.foo.bar.rest.ClientfeatureController  - client id: null

Let me also add that XML requests work just fine:

URL: ..http://localhost:8080/coreserviceswrapper/clientfeature.xml Method: POST/PUT Content-Type: text/xml

Payload:

<com.foo.bar.entity.ClientFeature>
<clientId>100</clientId>
<feature>
<description>test</description>
</feature>
</com.foo.bar.entity.ClientFeature>

Output:

1738685 [http-bio-8080-exec-7] INFO  com.foo.bar.rest.ClientfeatureController  - client id: 100
1738685 [http-bio-8080-exec-7] INFO  com.foo.bar.rest.ClientfeatureController  - feature description: test
1738717 [http-bio-8080-exec-7] INFO  org.apache.struts2.rest.RestActionInvocation  - Executed action [/clientfeature!create!xml!200] took 1466 ms (execution: 1436 ms, result: 30 ms)
2
Share some code to understand your questionRahul Agrawal
How many JSON formats are there?Dave Newton
Hi guys, I updated my question to hopefully be clearer. Thanks.shaunlim

2 Answers

1
votes

I also encounter same issue, my environment is: Structs 2.3.16.3, Jquery 1.11, Struts-rest-plugin symptom: post json data, rest controller not parse json data to model. solution: since the controller is modeldriven, browser client just post Json string is OK. but seems you have to force jquery to change conenttype of ajax call.

_self.update= function(model, callback) {  
          $.ajax({  
              beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
              type: 'PUT',  
              url: this.svrUrl+"/"+ model.id + this.extension,  
              data: JSON.stringify(model), // '{"name":"' + model.name + '"}',  
              //contentType: this.contentType,
              //dataType: this.dataType,  
              processData: false,                   
              success: callback,  
              error: function(req, status, ex) {},  
              timeout:60000  
          });  
      };  

the model data format is : var model = {"id":"2", "name":"name2", "author":"author2", "key":"key2" }

when you put or post data whit "Content-Type"="application/json", the plugin will handle it with Jsonhandler automatically.

0
votes

I got such a problem. Strange but got solved by changing the name 'clientFeature' to 'model'