如何在struts2中解析json属性

时间:2013-11-04 03:57:44

标签: struts2-json-plugin

当我将“name”属性保存为简单字符串数据时,以下代码正常工作, 但现在我想将“名称”保存为JSON数据,例如 {“en”:“白米”,“cn”:“白米”,“th”:“ข้าวขาว”},并根据区域语言显示名称值。我该怎么办?

<s:iterator value="categorylist">
    <li class="mn_menu-active">
        <a href="#"> 
              <span><s:property value="name" /></span>

              <div class="clear"></div>
              </a>
              <ul>
                <s:iterator value="children">
                    <li>
                        <a href="#">
                         <span class="ms_txt"><s:property value="name" /></span>
                         <div class="clear"></div>
                         </a>
                     </li>

                </s:iterator>
              </ul>

          </li>
</s:iterator>

1 个答案:

答案 0 :(得分:0)

听我实现一个类来处理它。

包com.tsd.json;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.util.ValueStack;

import java.util.Locale;

import net.sf.json.JSONObject;

public class LocaleHandler {

public static String Locale(String name)
{
    ValueStack stack = ActionContext.getContext().getValueStack();


    String result="";
    HttpServletRequest request = ServletActionContext.getRequest();
    Locale locale = (java.util.Locale)request.getSession().getAttribute("WW_TRANS_I18N_LOCALE");
    String jsonData =(String)stack.findValue(name);
    JSONObject json=JSONObject.fromObject(jsonData); 
     if(locale ==null)
     {
         HttpServletResponse response=ServletActionContext.getResponse();
         locale=response.getLocale();
     }
     if (locale instanceof Locale)
     {
         result= json.getString(locale.getLanguage()+"_"+locale.getCountry());
     }
    return result;
}

}

并按如下方式修改jsp:

 <s:iterator value="categorylist">
              <li class="mn_menu-active">
                  <a href="#"> 
                     <span>
                       <%=LocaleHandler.Locale("name") %>
                     </span>

                     <div class="clear"></div>
                  </a>
                  <ul>
                    <s:iterator value="children">
                        <li>
                            <a href="#">
                             <span class="ms_txt"> <%=LocaleHandler.Locale("name") %></span>
                             <div class="clear"></div>
                             </a>
                         </li>

                    </s:iterator>
                  </ul>

              </li>
          </s:iterator>