How to make an Action to accept dynamic JSON data from the user interface in Struts 2?

Post them as content with type "application/json". You may do it with a simple jQuery Ajax call where you could specify the content-type and dataType.

$.ajax({
   type: "POST",
   url: "/the/action/url",     
   data : {},
   dataType:"JSON",
   contentType: "application/json; charset=utf-8"
});

Add json plugin to the project dependencies with json-lib-2.3-jdk15.jar. The plugin supplied with the interceptor json that reads and populates an action from the request.

If you don’t want to populate the action then you should not use this interceptor. Instead manually parse the request with this or any other third party library to get the JSONObject class. Or you could rewrite the interceptor and comment that code that is using JSONPopulator class but deserialize the object with JSONUtil class.

Also, you might find this examples useful when manually creating/parsing JSON data.

Leave a Comment