jackson 使用方法

jackson须要3个jar: jackson-annotations   jackson-core   jackson-databind  版本本身找吧。java

用过的版本。json

只是简单讲解ObjectMapper的使用数组

ObjectMapper API:app

1.java对象转成json字符串or其余的ui

import java.io.IOException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
  
import com.fasterxml.jackson.databind.ObjectMapper; 
  
public class JacksonDemo { 
  public static void main(String[] args) throws ParseException, IOException { 
    User user = new User(); 
    user.setName("小民");  
    user.setEmail("xiaomin@sina.com"); 
    user.setAge(20); 
      
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); 
    user.setBirthday(dateformat.parse("1996-10-01"));     
      
    /** 
     * ObjectMapper是JSON操做的核心,Jackson的全部JSON操做都是在ObjectMapper中实现。 
     * ObjectMapper有多个JSON序列化的方法,能够把JSON字符串保存File、OutputStream等不一样的介质中。 
     * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。 
     * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。 
     * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。 
     * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。 
     */
    ObjectMapper mapper = new ObjectMapper(); 
      
    //User类转JSON 
    //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"} 
    String json = mapper.writeValueAsString(user); 
    System.out.println(json); 
      
    //Java集合转JSON 
    //输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}] 
    List<User> users = new ArrayList<User>(); 
    users.add(user); 
    String jsonlist = mapper.writeValueAsString(users); 
    System.out.println(jsonlist); 
  } 
}

例 writeValue():
mapper.writeValue(new File("c:\\user.json"), user); //指定文件写入spa

 

2.json字符串转javacode

readValue(json,args)  json :json字符串  args:对象类型可包括List.class    Map.class User.class User[ ].class(数组对象)orm

:"[{"uid":1,"uname":"www","number":234,"upwd":"456"}, {"uid":5,"uname":"tom","number":3.44,"upwd":"123"}]"xml

 

代码块黑色很差看就用文本了对象

import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class JacksonDemo {
  public static void main(String[] args) throws ParseException, IOException {
    String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";
      
    /**
     * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
     */
    ObjectMapper mapper = new ObjectMapper();
    User user = mapper.readValue(json, User.class);
    System.out.println(user);
  }
}

readValue同样能够从流里读
        File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");  
         FileInputStream inputStream = new FileInputStream(file);  
         Student student = mapper.readValue(inputStream,Student.class);

------------------------------------------------------------------------------------------------------------

相关文章
相关标签/搜索