5

I want to pass JSON array from Struts 2 action class to JSP page. I'm trying to send the data set as a string. The thing I want to know is, How can I read those data in JavaScript.

This is my method in Action class:

private InputStream inputStream;

/* getter and setter*/

public String getClientMilestone() throws DAOTransientException, DBConfigException{
        PaymentScheduleDao paymentScheduleDao = new PaymentScheduleDao();
        List <PaymentMilestone> paymentScheduleInfo = paymentScheduleDao.getClientMilestoneInfo(projectId);
        String result = "[";

        for(int i=0; i<paymentScheduleInfo.size(); i++){
            
            result += "{"+"'"+"item"+i+"' : {"+ "'"+"milestoneName"+ "'"+":"+"'"+paymentScheduleInfo.get(i).getMilestone_name()+"'"+"}"+"},";
            
        }
        result += "]";
        System.out.println("result is "+result);
        inputStream = new StringBufferInputStream(result);
        return "success";
    }

It prints as below:

result is [{'item0' : {'milestoneName':'milestone 1'}},{'item1' : {'milestoneName':'milestone 2'}}]

struts.xml:

<package name="ClientMilestone" namespace="/" extends="struts-default">
        <action name="getClientMilestone" class="packageName.PaymentScheduleAction" method="getClientMilestone">
            <result name="success" type="stream">
            <param name="contentType">text/html</param>
            <param name="inputName">inputStream</param>
            </result>
            <result name="failure">./LandingPage.jsp</result>
            <result name="error">./Error.jsp</result>
        </action>
    </package>

JavaScript function in JSP:

function createOrViewPs() {
    
    var projectId = document.getElementById("projectId").value;
    $.ajax({ 
        method: "GET",
        url: "getClientMilestone",
        data: {"projectId" : projectId},
        traditional: true, 
        success:
            function(result){
                var jsonArr = result;
            
                for (var i=0; i<jsonArr.length; i++)
                    for (var name in jsonArr[i]) {
                        alert("Item name: "+name);
                        alert("Source: "+jsonArr[i][name].milestoneName);
                }
            },
        error: 
            function(){
                alert("fail");
            }
    });         
} 
Roman C
  • 49,761
  • 33
  • 66
  • 176
WCM
  • 595
  • 3
  • 11
  • 27

1 Answers1

1

Because you return a stringified version of JSON from the server with the stream result type (Note, that stream result type might not be appropriate, see below), you need to parse it to JSON with JSON.parse() and if you are using jQuery better use $.each

var jsonArr = JSON.parse(result);
$.each (jsonArr, function(index, value){
  $.each (value, function(key, value){
    console.log("Item name: "+key);
    console.log("Source: "+value.milestoneName);
  });
});

What you did wrong is building json manually. You should use a tool that serializes Java object to JSON. Struts2 has json-lib available jar in the package that can be used to serialize to json, or if you are using struts2-json-plugin then it has built-in serializer. if you are using struts2-rest-plugin then you can use other serializer like Jackson. The way you choose the library to serialize your data is out of the scope of this answer. You can find many examples on SO and on Struts site. Most of them using json plugin that returns JSON object that supports by the browser, i.e. doesn't need parsing, however parsing for JSON is useful to avoid errors and data lose.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I am using struts2-json-plugin. As you have told I create json object and then put those object into json array.Then I send those array to jQuery as above. But in console "Item name" is ok. Source is "undefined". – WCM Apr 05 '17 at 06:08
  • I didn't see it in the question. Also I didn't tell you *create json object and then put those object into json array*. I said **You should use a tool that serializes Java object to JSON.** – Roman C Apr 05 '17 at 07:56
  • problem solved. Thank you. By the way, Is there a way to pass date via json array – WCM Apr 05 '17 at 08:17
  • May be [this](http://stackoverflow.com/a/35706457/573032) or [this](http://stackoverflow.com/a/27686588/573032). Better if you ask a full fledged question. – Roman C Apr 05 '17 at 09:17