Jackson. Jar usage record

Source: Internet
Author: User

Jackson. Jar usage record

I 've been using json-lib.jar before, and recently found online that this Jackson. jar is better

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;@Controllerpublic 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对象转为jsonUserJson 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集合转为jsonList<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;}}

Convert list to JSON array (Java Main Program)

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 writeValueAsStringString 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 Bytesbyte[] 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 ByteArrayOutputStreamfinal 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 writeValueAsStringString jsonArray = mapper.writeValueAsString(list);System.out.println(jsonArray);return jsonArray;}}

JSP page:

<%@ 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">




Jackson. Jar usage record

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.