本篇主要演示如何使用Jackson对List, Map和数组与JSON互相转换.

package
  
import
import
import
import
import
import
import
  
import
import
  
public class
  
public static void main(String[] args) throws
new
5237);  
"jingshou");  
new
          
new
5117);    
"saiya");    
new
          
new
            
//Convert between List and JSON
new
        stuList.add(student1);  
        stuList.add(student3);  
        String jsonfromList = mapper.writeValueAsString(stuList);  
        System.out.println(jsonfromList);  
          
//List Type is not required here.
class);  
        System.out.println(stuList2);      
"************************************");  
          
//Convert Map to JSON
new
"studentList", stuList);  
"class", "ClassName");  
        String jsonfromMap =  mapper.writeValueAsString(map);  
        System.out.println(jsonfromMap);  
          
class);  
        System.out.println(map2);  
"studentList"));      
"************************************");     
          
//Convert Array to JSON
        Student[] stuArr = {student1, student3};  
        String jsonfromArr =  mapper.writeValueAsString(stuArr);  
        System.out.println(jsonfromArr);   
class);  
        System.out.println(Arrays.toString(stuArr2));  
    }  
  
}


 运行结果:

[{"id":5237,"name":"jingshou","birthDay":1389528275987},{"id":5117,"name":"saiya","birthDay":1389528275987}]  
[{id=5237, name=jingshou, birthDay=1389528275987}, {id=5117, name=saiya, birthDay=1389528275987}]  
************************************  
{"class":"ClassName","studentList":[{"id":5237,"name":"jingshou","birthDay":1389528275987},{"id":5117,"name":"saiya","birthDay":1389528275987}]}  
{class=ClassName, studentList=[{id=5237, name=jingshou, birthDay=1389528275987}, {id=5117, name=saiya, birthDay=1389528275987}]}  
[{id=5237, name=jingshou, birthDay=1389528275987}, {id=5117, name=saiya, birthDay=1389528275987}]  
************************************  
[{"id":5237,"name":"jingshou","birthDay":1389528275987},{"id":5117,"name":"saiya","birthDay":1389528275987}]  
[Student [birthDay=Sun Jan 12 20:04:35 CST 2014, id=5237, name=jingshou], Student [birthDay=Sun Jan 12 20:04:35 CST 2014, id=5117, name=saiya]]


 

再举一例实际应用:

小米网站注册页面输入邮件地址后,服务器提交的Ajax请求是:

https://account.xiaomi.com/pass/user@externalIdBinded?externalId=9999999%40qq.com&type=EM

服务器的返回是: &&&START&&&{"result":"ok","description":"成功","data":{"userId":-1},"code":0}

我们可以尝试用Map去读取后面那一段JSON

package
  
import
import
  
import
import
import
  
public class
  
public static void main(String[] args) throws
"{\"result\":\"ok\",\"description\":\"成功\",\"data\":{\"userId\":-1},\"code\":0}";  
new
class);  
//输出 {result=ok, descriptinotallow=成功, data={userId=-1}, code=0}
        System.out.println(map);  
//输出{userId=-1}
"data");  
        System.out.println(dataMap);          
    }  
  
}

 

可见以Key-Value形式的JSON字符串,都可以直接使用Map成功读取出来