使用jackson的writeValueAsString把java对象输出成字符串实例,设置应答体的类型

来源:互联网 发布:淘宝如何发布商品 编辑:程序博客网 时间:2024/06/05 15:36

转载地址:http://www.360sdn.com/json/2013/0525/216.html

+http://hw1287789687.iteye.com/blog/2188480


要使用jackson的json解析器需要下载jackson的核心jar包:

jackson-core-2.2.0.jar jackson-core下载地址

jackson-annotations-2.2.0.jar jackson-annotations下载地址

jackson-databind-2.2.0.jar  jackson-databind下载地址

一、首先定义一个java的pojo类,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com;
 
public class BaseObject {
   privateString userName;
   privateString userCode;
   privatedouble weight;
   privateint height;
   privateboolean sex;
   privateString[] array;
   privateBaseObject  innerObject;
public String getUserName() {
    returnuserName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public String getUserCode() {
    returnuserCode;
}
public void setUserCode(String userCode) {
    this.userCode = userCode;
}
public double getWeight() {
    returnweight;
}
public void setWeight(doubleweight) {
    this.weight = weight;
}
public int getHeight() {
    returnheight;
}
public void setHeight(intheight) {
    this.height = height;
}
public boolean isSex() {
    returnsex;
}
public void setSex(booleansex) {
    this.sex = sex;
}
  
public BaseObject getInnerObject() {
    returninnerObject;
}
public void setInnerObject(BaseObject innerObject) {
    this.innerObject = innerObject;
}
public String[] getArray() {
    returnarray;
}
public void setArray(String[] array) {
    this.array = array;
}
    
    
}

二、把java的pojo类输出成json字符串

使用jackson的ObjectMapper 的writeValueAsString方法可以把pojo类输出成json字符串,代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.BaseObject;
 
public class JacksonJsonTest {
     publicstatic void main(String[] args){ 
          JacksonJsonTest jsonImple=newJacksonJsonTest(); 
          try{  
          ObjectMapper mapper =new ObjectMapper(); 
          List dataList=newArrayList();
          Map<string,object> map =new HashMap<string, object="">();
            BaseObject object1=newBaseObject();
            object1.setUserName("张三");
            object1.setWeight(65.5);
            object1.setHeight(170);
            object1.setSex(true);
            String[] score={"80","90","95"};
            object1.setArray(score);
            BaseObject object2=newBaseObject(); 
            object2.setUserName("李四");
            object2.setWeight(75.5);
            object2.setHeight(171);
            object2.setSex(true);
            score=newString[3];
            score[0]="65";
            score[1]="68";
            score[2]="75";
            object2.setArray(score);
            object1.setInnerObject(object2);
            dataList.add(object1);
            map.put("baseObject", dataList); 
            String json=mapper.writeValueAsString(object1);
            System.out.println(json);
           
          }
          catch(Exception ex){
               
          
      }
}
 
 
</string,></string,object>

输出的结果如下:

{"userName":"王五","userCode":null,"weight":65.5,
"height":170,"sex":true,"array":["语文:85",
"数学:80","英语:95"],"innerObject":{"userName":"赵六",
"userCode":null,"weight":75.5,"height":171,"sex":true,
"array":["语文:65","数学:68","英语:75"],"innerObject":null}}





spring MVC中如何设置应答体的content type呢?

spring MVC中如何设置返回类型呢?

我们知道response 的content type主要有:

text/html

text/plain

application/json;charset=UTF-8

application/octet-stream

先举一个例子,spring mvc中可以通过如下方式返回json字符串:

Java代码  收藏代码
  1. @ResponseBody  
  2.     @RequestMapping(value = "/upload")  
  3.     public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)  
  4.             throws IOException {  
  5.         String content = null;  
  6.         Map map = new HashMap();  
  7.         ObjectMapper mapper = new ObjectMapper();  
  8.   
  9.         map.put("fileName", "a.txt");  
  10.         try {  
  11.             content = mapper.writeValueAsString(map);  
  12.             System.out.println(content);  
  13.         } catch (JsonGenerationException e) {  
  14.             e.printStackTrace();  
  15.         } catch (JsonMappingException e) {  
  16.             e.printStackTrace();  
  17.         } catch (IOException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.           
  21.         return content;  
  22.   
  23.     }  

 虽然访问时返回的确实是json字符串,但是response 的content type是"

text/html

"这不是我们期望的,我们期望的response content type是"application/json"或者"application/json;charset=UTF-8",那么如何实现呢?

通过注解@RequestMapping 中的produces

用法如下:

Java代码  收藏代码
  1. @RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")  

 spring MVC官方文档:

Producible Media Types

You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:

@Controller@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")@ResponseBodypublic Pet getPet(@PathVariable String petId, Model model) {    // implementation omitted}

Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.

Tip[Tip]

The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.



0 0
原创粉丝点击