Alibaba Jackson's Objectmapper tool class package

Source: Internet
Author: User
Tags json

A tool class that goes to the learning video:

Package com.example.demo.test;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;

Import java.util.List;


Import Org.apache.commons.lang3.StringUtils;
Import Com.fasterxml.jackson.annotation.JsonInclude.Include;
Import Com.fasterxml.jackson.databind.DeserializationFeature;
Import Com.fasterxml.jackson.databind.JavaType;
Import Com.fasterxml.jackson.databind.ObjectMapper;
Import Com.fasterxml.jackson.databind.SerializationFeature;

Import com.fasterxml.jackson.core.type.TypeReference;
	
	public class Jsonutils {private static Objectmapper Objectmapper = new Objectmapper ();
        static {//All field serialization//All fields of the object are all included in Objectmapper.setserializationinclusion (Include.always);
        Cancels the default conversion timestamps form objectmapper.configure (Serializationfeature.write_dates_as_timestamps,false);
		All date formats are unified into the following styles, i.e. Yyyy-mm-dd HH:mm:ss objectmapper.setdateformat ("Yyyy-mm-dd HH:mm:ss"); Error objectmapper.configure ignoring empty bean to JSON (SerialiZationfeature.fail_on_empty_beans,false); Ignoring the existence of a JSON string, but there is no corresponding attribute in the Java object.
	Prevent error Objectmapper.configure (DESERIALIZATIONFEATURE.FAIL_ON_UNKNOWN_PROPERTIES,FALSE);
            }/** * * @param obj * @return */public static <T> String obj2string (T obj) {if (obj = = null) {
        return null; } try {return obj instanceof String?
        (String) obj:objectMapper.writeValueAsString (obj);
            } catch (Exception e) {e.printstacktrace ();
        return null; }}/** * formatted * @param obj * @return */public static <T> String obj2stringpretty (T obj) {i
        F (obj = = null) {return null; } try {return obj instanceof String?
        (String) Obj:objectMapper.writerWithDefaultPrettyPrinter (). writevalueasstring (obj);
            } catch (Exception e) {e.printstacktrace ();
        return null; }}/** * String to Object * @param str * @pAram Clazz * @return * * public static <T> T string2obj (String str,class<t> clazz) {if (stringutils . IsEmpty (str) | |
        Clazz = = null) {return null; } try {return clazz.equals (string.class)?
        (T) Str:objectMapper.readValue (Str,clazz);
            } catch (Exception e) {e.printstacktrace ();
        return null; }}/** * field character to list such as collection * @param str * @param typereference * @return */public static <T> T Strin
            G2obj (String str, typereference typereference) {if (Stringutils.isempty (str) | | | typereference = NULL) {
        return null; } try {return (T) (Typereference.gettype (). Equals (String.class)? Str:objectMapper.readValue (Str,type
        Reference));
            } catch (Exception e) {e.printstacktrace ();
        return null;
}}/** * Almost ditto * @param str * @param collectionclass * @param elementclasses * @return * *	public static <T> T string2obj (String str,class<?> collectionclass,class<?> ... elementclasses) {
        Javatype Javatype = Objectmapper.gettypefactory (). Constructparametrictype (collectionclass,elementclasses);
        try {return objectmapper.readvalue (Str,javatype);
            } catch (Exception e) {e.printstacktrace ();
        return null;
		}} public static void Main (string[] args) {jsonutils js = new Jsonutils ();
		User U = New User (1L, "YWJ", 123, New Date ());
		User U2 = new user ();
		System.out.println (js.obj2string (U));
		System.out.println (Js.obj2stringpretty (U2));
		
		String str = js.obj2string (u);
		User U3 = js.string2obj (str, user.class);
		System.out.println (U3.getname ()); Added attribute minus attribute User U5 = js.string2obj ("{\" id\ ": 1,\" name\ ": \" ywj\ ", \" age2222\ ": 123,\" date\ ": \" 2018-01-14 22:14:18\ ", \"
		Abc\ ": \" Abc\ "}", User.class);
		
		System.out.println (U5.getname ()); list<user> list = new Arraylist<user> ();
		List.add (New User (1L, "YWJ", 123, New Date ()));
		List.add (New User (2L, "Ywj2", 123, New Date ()));
		str = js.obj2string (list);
		
		System.out.println (str);
		List = Js.string2obj (str, new typereference<list<user>> () {});
		
		System.out.println (list.size () + ":" +list.get (1). GetName ());
		List = Js.string2obj (str, list.class, user.class);
	System.out.println (list.size () + ":" +list.get (1). GetName ());
 }
}

Ok

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.