之前一直使用json-lib.jar,最近发现网上说这个jackson.jar比较好
package com.spring.controller; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class JacksonController { @RequestMapping(value="user/jackson", method = {RequestMethod.POST,RequestMethod.GET}) public ModelAndView PostJsonTest(HttpServletRequest request,HttpServletResponse response) throws IOException{ ModelAndView mav=new ModelAndView(); mav.addObject("time", new Date()); JsonGenerator jsonGenerator = null; ObjectMapper objectMapper = new ObjectMapper(); jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8); //将java对象转为json UserJson userJson=new UserJson(); userJson.setUsername("小米"); userJson.setId("31231"); userJson.setPwd("123456"); userJson.setAge(24); userJson.setAddress("广州"); userJson.setTel(13676586); //objectMapper.writeValue(jsonGenerator, userJson); String jsonStr = objectMapper.writeValueAsString(userJson); //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等 //jsonGenerator.writeObject(userJson); System.out.println("-----json-------"); String jsonSS="{\"address\":\"广州\",\"id\":\"31231\",\"username\":\"小米\",\"tel\":13676586,\"age\":24,\"pwd\":\"123456\"}"; System.out.println("--------字符串json-------"+jsonSS); System.out.println("------标准jsonStr--------"+jsonStr); mav.addObject("jsonStr", jsonStr); mav.addObject("jsonss", jsonSS.toString()); mav.setViewName("json/jackson"); //将list集合转为json List<UserJson> list=new ArrayList<UserJson>(); for(int i=0;i<5;i++){ UserJson u3=new UserJson(); u3.setId("ooo"+i); u3.setUsername("小小明"+i); u3.setPwd("123456"+i); u3.setAge(20+i); u3.setAddress("广州"+i); u3.setTel(13664+i*i*i); list.add(u3); } String jsonlist = objectMapper.writeValueAsString(list); mav.addObject("jsonlist", jsonlist.toString()); mav.setViewName("json/jackson"); return mav; } /** * list转为json数组 */ public String writeListToJsonArray() throws IOException { /*List<Event> list = new ArrayList<Event>(2); list.add(new Event("a1","a2")); list.add(new Event("b1","b2"));*/ List<String> list = new ArrayList<String>(); list.add("A2"); list.add("B2"); OutputStream out = new ByteArrayOutputStream(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(out, list); byte[] data = ((ByteArrayOutputStream) out).toByteArray(); System.out.println(new String(data)); String result=new String(data); return result; } /** * list转为json数组 */ public String writeListToJsonArray2() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); final ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A2"); list.add("B2"); String jsonArray = ow.writeValueAsString(list); System.out.println(jsonArray); return jsonArray; } } ///java对象 class UserJson{ private String id; private String username; private String pwd; private Integer age; private int tel; private String address; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public int getTel() { return tel; } public void setTel(int tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
list转为json数组(是Java main程序)
package com.main.java.demo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; public class JacksonDemo { public static void main(String args[]) throws IOException{ //writeListToJsonArray(); //writeListToJsonArray2(); //writeListToJsonArray3(); //writeListToJsonArray4(); //writeListToJsonArray5(); writeListToJsonArray6(); } /** * list转为json数组 */ public static String writeListToJsonArray() throws IOException { /*List<Event> list = new ArrayList<Event>(2); list.add(new Event("a1","a2")); list.add(new Event("b1","b2"));*/ /*List<String> list = new ArrayList<String>(); list.add("A2"); list.add("B2");*/ /*List<Integer> list = new ArrayList<Integer>(); list.add(12); list.add(45); list.add(5);*/ List<Float> list = new ArrayList<Float>(); list.add((float) 12.32); list.add((float) 45.12); list.add((float) 5.09); OutputStream out = new ByteArrayOutputStream(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(out, list); byte[] data = ((ByteArrayOutputStream) out).toByteArray(); System.out.println(new String(data)); String result=new String(data); return result; } /** * list转为json数组 */ public static String writeListToJsonArray2() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); final ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A2"); list.add("B2"); //// Using writeValueAsString String jsonArray = ow.writeValueAsString(list); System.out.println(jsonArray); return jsonArray; } /** * list转为json数组 */ public static String writeListToJsonArray3() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A23"); list.add("B23"); //// Using Bytes byte[] data = mapper.writeValueAsBytes(list); String jsonArray = new String(data, "UTF-8"); System.out.println(jsonArray); return jsonArray; } /** * list转为json数组 */ public static String writeListToJsonArray4() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A234"); list.add("B234"); // Using ByteArrayOutputStream with new String() OutputStream os = new ByteArrayOutputStream(); mapper.writeValue(os, list); byte[] data = ((ByteArrayOutputStream) os).toByteArray(); String jsonArray = new String(data, "UTF-8"); System.out.println(jsonArray); return jsonArray; } /** * list转为json数组 */ public static String writeListToJsonArray5() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A2345"); list.add("B2345"); // Using ByteArrayOutputStream final OutputStream os = new ByteArrayOutputStream(); mapper.writeValue(os, list); String jsonArray = ((ByteArrayOutputStream) os).toString("UTF-8"); System.out.println(jsonArray); return jsonArray; } /** * list转为json数组 */ public static String writeListToJsonArray6() throws IOException { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); ObjectMapper mapper = new ObjectMapper(); List<String> list = new ArrayList<String>(); list.add("A23456"); list.add("B23456"); // Using writeValueAsString String jsonArray = mapper.writeValueAsString(list); System.out.println(jsonArray); return jsonArray; } }
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'jackson.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="<%=basePath%>js/jquery.min.js"></script> </head> <body> <h3>Jackson 解析json</h3> <div><p>传过来的标准json字符串-----是一个json对象----</p>${jsonStr}</div> <div><p>传过来的json格式字符串-----是一个json对象-----</p>${jsonss}</div> <p>本页面造的json格式字符串------要转为json对象才能解析(还不是一个json对象)----</p> <div class="jsonHtml">{"address":"广州","id":"31231","username":"小米","tel":13676586,"pwd":"123456","age":24}</div> <div><p>传过来的jsonlist-----是一个json数组对象-----</p>${jsonlist}</div> </body> </html> <script type="text/javascript"> <!-- $(document).ready(function(){ /* //解析服务端传过来的标准json var jsonStr=${jsonStr};//是一个json对象 alert(jsonStr.username);//可以解析服务端传过来的json字符串,但解析不了页面造的字符串 //遍历json标准字符串 //var data=eval("("+jsonStr+")"); //alert(data.tel); //var jsonss=${jsonss};//是一个json对象,不用转为json对象,否则出错 //alert(jsonss);//是一个对象 //var item = jQuery.parseJSON(jsonss); //alert(item.address); var jsonHtml = $(".jsonHtml").html();//是一个字符串,要转为json对象 //alert(jsonHtml.tel);//解析不了页面造的字符串,但能解析服务端传过来的字符串 var item = jQuery.parseJSON(jsonHtml); alert(item.address); */ //解析listjson var jsonlist=${jsonlist}; alert(jsonlist.length); alert(jsonlist[0].username); for(var i=0;i<jsonlist.length;i++){ alert(jsonlist[i].username); } }); //--> </script>
时间: 2024-10-07 17:55:12