<< Hibernate的dynamic-insert与dynamic-update - 虫二的专栏~~在路上~~~ - 博客频道 - CSDN.NET | 首页 | Spring MVC and AJAX with JSON >>

Spring MVC 整合 JSON 视图

Jackson转换Java对象

1、 jackson有专门的视图MappingJacksonJsonView,只需用配置这个视图就可以完成转换json了。使用jackson需要添加如下jar包:

clip_image006

如果你对Jackson转换Java对象还没有什么了解的话,你可以参考:

For cnblogs:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html

For csdn:http://blog.csdn.net/IBM_hoojo/archive/2011/04/22/6340762.aspx

2、 然后需要在dispatcher.xml中添加视图配置,配置如下:

<bean name="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="encoding">
        <value type="org.codehaus.jackson.JsonEncoding">UTF8value>
    property>
    <property name="contentType" value="text/html;charset=UTF-8"/>
bean>

3、 将Java对象转换JSON

package com.hoo.controller;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hoo.entity.Account;
import com.hoo.entity.Brithday;
import com.hoo.entity.User;
 
/**
 * function:用MappingJacksonJsonView视图和Jackson转换Json
 * @author hoojo
 * @createDate 2011-4-28 下午04:52:23
 * @file JacksonJsonViewController.java
 * @package com.hoo.controller
 * @project SpringMVC4View
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@Controller
@RequestMapping("/jackson/view")
public class JacksonJsonViewController {
    
    /**
     * function:转换普通Java对象
     * @author hoojo
     * @createDate 2011-4-28 下午05:14:18
     * @return
     */
    @RequestMapping("/doBeanJsonView")
    public ModelAndView doBeanJsonView() {
        System.out.println("#################ViewController doBeanJsonView##################");
        ModelAndView mav = new ModelAndView("jsonView");
        User user = new User();
        user.setAddress("china GuangZhou");
        user.setAge(23);
        user.setBrithday(new Date());
        user.setName("jack");
        user.setSex(true);
        
        Account bean = new Account();
        bean.setAddress("北京");
        bean.setEmail("email");
        bean.setId(1);
        bean.setName("haha");
        Brithday day = new Brithday();
        day.setBrithday("2010-11-22");
        bean.setBrithday(day);
        
        mav.addObject(bean);
        return mav;
    }
}

上面使用了刚才我们配置的jsonView视图,通过这个视图就可以将ModelAndView中的数据转换成JSON数据。

在浏览器中请求:http://localhost:8080/SpringMVC4View/jackson/view/doBeanJsonView.do

结果如下:

{"account":{"address":"北京","name":"haha","id":1,"email":"email","brithday":{"brithday":"2010-11-22"}}}

4、 转换Map到JSON

/**
 * function:转换Map集合
 * @author hoojo
 * @createDate 2011-4-28 下午05:14:33
 * @return
 */
@RequestMapping("/doMapJsonView")
public ModelAndView doMapJsonView() {
    System.out.println("#################ViewController doBeanJsonView##################");
    ModelAndView mav = new ModelAndView("jsonView");
    User user = new User();
    user.setAddress("china GuangZhou");
    user.setAge(23);
    user.setBrithday(new Date());
    user.setName("jack");
    user.setSex(true);
    Map
    map.put("user", user);
    map.put("success", true);
    mav.addObject(map);
    mav.addObject("title", "ViewController doBeanJsonView");
    return mav;
}

在WebBrowser中请求:http://localhost:8080/SpringMVC4View/jackson/view/doMapJsonView.do

结果如下:

{"hashMap":{"success":true,"user":{"address":"china GuangZhou","name":"jack","age":23,"sex":true,"brithday":1303982296953}},
"title":"ViewController doBeanJsonView"}

5、 转换List到JSON

/**
 * function:转换List集合
 * @author hoojo
 * @createDate 2011-4-28 下午05:14:54
 * @return
 */
@RequestMapping("/doListJsonView")
public ModelAndView doListJsonView() {
    System.out.println("#################ViewController doBeanJsonView##################");
    ModelAndView mav = new ModelAndView("jsonView");
    List<User> list = new ArrayList<User>();
    for (int i = 0; i < 3; i++) {
        User user = new User();
        user.setAddress("china GuangZhou#" + i);
        user.setAge(23 + i);
        user.setBrithday(new Date());
        user.setName("jack_" + i);
        user.setSex(true);
        list.add(user);
    }
    
    mav.addObject(list);
    return mav;
}

在浏览器中请求http://localhost:8080/SpringMVC4View/jackson/view/doListJsonView.do

结果如下:

{"userList":[{"address":"china GuangZhou#0","name":"jack_0","age":23,"sex":true,"brithday":1303982399265},
{"address":"china GuangZhou#1","name":"jack_1","age":24,"sex":true,"brithday":1303982399265},
{"address":"china GuangZhou#2","name":"jack_2","age":25,"sex":true,"brithday":1303982399265}]}

总结,spring对jackson提供了专门的视图,整合起来也比较方便。而且jackson也比较简单易用。

 

七、 JSON-lib转换JavaJSON

1、 Spring没有提供JSON-lib的view视图,不过没有关系。我们可以自己扩展一个,只需用继承AbstractView类,实现里面的方法就可以了。首先你需要了解JSON-lib,如果你还不了解JSON-lib的话,建议阅读:

For cnblogs: http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html

For csdn: http://blog.csdn.net/IBM_hoojo/archive/2011/04/21/6339246.aspx

然后你需要在工程中添加如下jar文件:

clip_image008

2、 因为Spring没有提供view,我们需要自己实现一个。代码如下:

package com.hoo.veiw.xml;
 
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;
 
/**
 * function:扩展AbstractView 实现JSON-lib视图
 * @author hoojo
 * @createDate 2011-4-28 下午05:26:43
 * @file MappingJsonlibVeiw.java
 * @package com.hoo.veiw.xml
 * @project SpringMVC4View
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public class MappingJsonlibVeiw extends AbstractView {
    
    public static final String DEFAULT_CONTENT_TYPE = "application/json";
    
    public static final String DEFAULT_CHAR_ENCODING = "UTF-8";
 
    private String encodeing = DEFAULT_CHAR_ENCODING;
 
    public void setEncodeing(String encodeing) {
        this.encodeing = encodeing;
    }
 
    private Set renderedAttributes;
    
    private JsonConfig cfg = null;
    
    public void setCfg(JsonConfig cfg) {
        this.cfg = cfg;
    }
 
    public MappingJsonlibVeiw() {
        setContentType(DEFAULT_CONTENT_TYPE);
    }
    
    @Override
    protected void renderMergedOutputModel(Map
            HttpServletResponse response) throws Exception {
        model = filterModel(model);
        response.setCharacterEncoding(encodeing);
        
        PrintWriter out = response.getWriter();
        if (cfg == null) {
            out.print(JSONSerializer.toJSON(model));
        } else {
            out.print(JSONSerializer.toJSON(model, cfg));
        }
    }
 
    /**
     * Filters out undesired attributes from the given model.
     * 

Default implementation removes {@link BindingResult} instances and entries not included in the {@link

     * #setRenderedAttributes(Set) renderedAttributes} property.
     */
    protected Map
        Map
        Set renderedAttributes =
                !CollectionUtils.isEmpty(this.renderedAttributes) ? this.renderedAttributes : model.keySet();
        for (Map.Entry
            if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }
}

上面的代码不是很复杂,首先我们设置contentType,这个属性在AbstractView这个父类中有setter方法可以完成设置。

然后就是默认的编码格式,这个编码格式设置到response上。默认UTF-8编码。在renderMergedOutputModel方法中可以看到设置。

第三就是filterModule方法,这个方法是得到ModelAndView中我们添加对象,过滤掉BindingResult的信息。

最后就是renderMergedOutputModel方法,这个方法最为核心,但也很简单。过滤model获得要转换的model数据,设置response编码格式。利用response的Writer输出JSON信息,通过JSONSerializer转换Java到JSON。

3、 在dispatcher.xml中配置jsonlibView这个视图

<-- 自定义JSONlib的json视图 -->
<bean name="jsonlibView" class="com.hoo.veiw.xml.MappingJsonlibVeiw">
    <property name="contentType" value="text/html;charset=UTF-8"/>
    <property name="encodeing" value="gbk"/>
bean>

4、 转换普通Java对象

package com.hoo.controller;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hoo.entity.Account;
import com.hoo.entity.Brithday;
import com.hoo.entity.User;
 
/**
 * function:
 * @author hoojo
 * @createDate 2011-4-28 下午05:58:02
 * @file JsonlibMappingViewController.java
 * @package com.hoo.controller
 * @project SpringMVC4View
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@Controller
@RequestMapping("/jsonlib/view")
public class JsonlibMappingViewController {
    /**
     * function:转换普通Java对象
     * @author hoojo
     * @createDate 2011-4-28 下午05:14:18
     * @return
     */
    @RequestMapping("/doBeanJsonView")
    public ModelAndView doBeanJsonView() {
        System.out.println("#################ViewController doBeanJsonView##################");
        ModelAndView mav = new ModelAndView("jsonlibView");
        User user = new User();
        user.setAddress("china GuangZhou");
        user.setAge(23);
        user.setBrithday(new Date());
        user.setName("jack");
        user.setSex(true);
        
        Account bean = new Account();
        bean.setAddress("北京");
        bean.setEmail("email");
        bean.setId(1);
        bean.setName("haha");
        Brithday day = new Brithday();
        day.setBrithday("2010-11-22");
        bean.setBrithday(day);
        
        mav.addObject(bean);
        return mav;
    }
}

在WebBrowser中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doBeanJsonView.do

结果如下:

{"account":{"address":"北京","brithday":{"brithday":"2010-11-22"},"email":"email","id":1,"name":"haha"}}

5、 转换Map到JSON

/**
 * function:转换Map集合
 * @author hoojo
 * @createDate 2011-4-28 下午05:14:33
 * @return
 */
@RequestMapping("/doMapJsonView")
public ModelAndView doMapJsonView() {
    System.out.println("#################ViewController doBeanJsonView##################");
    ModelAndView mav = new ModelAndView("jsonlibView");
    User user = new User();
    user.setAddress("china GuangZhou");
    user.setAge(23);
    user.setBrithday(new Date());
    user.setName("jack");
    user.setSex(true);
    Map
    map.put("user", user);
    map.put("success", true);
    mav.addObject(map);
    mav.addObject("title", "ViewController doBeanJsonView");
    return mav;
}

在WebBrowser中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doMapJsonView.do

结果如下:

{"hashMap":{"success":true,"user":{"address":"china GuangZhou","age":23,
"brithday":{"date":28,"day":4,"hours":18,"minutes":20,"month":3,"seconds":8,
"time":1303986008703,"timezoneOffset":-480,"year":111},"name":"jack","sex":true}},
"title":"ViewController doBeanJsonView"}

发现时间被分解成一个对象了,这里需要用JSONConfig的JsonValueProcessor将brithday过滤下,然后用SimpleDateFormate进行格式转换。

6、 转换List集合

/**
 * function:转换List集合
 * @author hoojo
 * @createDate 2011-4-28 下午05:14:54
 * @return
 */
@RequestMapping("/doListJsonView")
public ModelAndView doListJsonView() {
    System.out.println("#################ViewController doBeanJsonView##################");
    ModelAndView mav = new ModelAndView("jsonlibView");
    List<User> list = new ArrayList<User>();
    for (int i = 0; i < 3; i++) {
        User user = new User();
        user.setAddress("china GuangZhou#" + i);
        user.setAge(23 + i);
        user.setBrithday(new Date());
        user.setName("jack_" + i);
        user.setSex(true);
        list.add(user);
    }
    
    mav.addObject(list);
    return mav;
}

在浏览器中请求http://localhost:8080/SpringMVC4View/jsonlib/view/doListJsonView.do

结果如下:

{"userList":[{"address":"china GuangZhou#0","age":23,"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,
"time":1303988574328,"timezoneOffset":-480,"year":111},"name":"jack_0","sex":true},
{"address":"china GuangZhou#1","age":24,"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,
"time":1303988574328,"timezoneOffset":-480,"year":111},"name":"jack_1","sex":true},{"address":"china GuangZhou#2","age":25,
"brithday":{"date":28,"day":4,"hours":19,"minutes":2,"month":3,"seconds":54,"time":1303988574328,"timezoneOffset":-480,"year":111},
"name":"jack_2","sex":true}]}

 

标签 : ,



发表评论 发送引用通报