related AddressesJackson Home Page:https://github.com/fasterxml/jackson
Jackson Wiki:http://wiki.fasterxml.com/jacksonhome
Jackson Doc:https://github.com/fasterxml/jackson-docs
Jackson Download Page:http://wiki.fasterxml.com/jacksondownload
Brief IntroductionJackson is a set of data processing tools for the Java platform, which can refer to the official website:
including the flagship streaming JSON Parser/generator Library, matching data-binding library (POJOs to and from JSO N) and additional data format modules to process data encoded in Avro, Bson, Cbor, CSV, Smile, Protobuf, XML or YAML; And even the large set of data format modules to support data types of of widely used data types such as Joda, guava and many , many more.Jackson has two main branches, 1.x is in maintenance and only the bug fix version is released. 2.x is also actively developing. These two versions of Java package names are not the same as Maven artifact, so they are not compatible, but can coexist peacefully, that is, the project can rely on 1.x and 2.x without conflict, this article will simply describe the use of the 2.x version.
Jackson Main module
Core ModulesThe core module is the foundation of the expansion module building, to 2.7, a total of 3 core modules:
Streaming: The Jackson-core jar, which defines the underlying streaming API and implements the JSON feature.
Annotations: The Jackson-annotations jar contains the standard Jackson annotation. This article is not introduced.
Databind: Jackson-databind jar, which implements data binding and object serialization, and relies on streaming and annotations packages.
third-party data type moduleThese extensions are plug-in Jackson modules that are registered with Objectmapper.registermodule () and are added serializers and deserializers to DataBind packages (Objectmapper/ Objectreader/objectwriter) can read and write these types to increase support for the data types of the various common Java libraries. Reference Https://github.com/FasterXML/jacksonThird-party datatype modules.
Data Format ModuleJackson also has handlers that provide data format support for JAX-RS standard implementations such as Jersey, Resteasy, and CXF. The handler implements Messagebodyreader and Messagebodywriter, and the data formats currently supported include JSON, Smile, XML, Yaml, and Cbor. Data formats provide support for data formats other than JSON, most of which only implement the streaming API abstractions so that data-binding components can be used in the same way. Other (almost unwanted) DataBind standard features are provided to handle such as schemas. Reference Https://github.com/FasterXML/jackson
Data Format Modules
preparatory workJackson contains a core jar package and two other jar packages that depend on the core jar package, from top to bottom, as follows:
Jackson Core
Jackson annotations
Jackson Databind
You can download the Jackson jar package from Https://github.com/FasterXML or use MAVEN to manage it. If it's a maven way, you need to add the following dependencies:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-core</artifactid>
<version>2.7.4</version>
</dependency>
< dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-annotations</artifactid>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-databind</artifactid>
<version>2.7.4</version>
</dependency>
working with JSONThis article uses the JDK7.0 version. Jackson offers three alternative JSON processing methods: Data binding (Binding), streaming API (streaming API), tree model.
Data BindingWe use objectmapper primarily to manipulate JSON, and by default we use Beanserializer to serialize Pojo. If it is parsing, then the Testjson in the following example must have setters, and setters must be public decorated, otherwise the value of the property will be null. If it is a build, then there must be getters, and getters must be public-decorated. If the property is not private, you can use getters and setters. This reference access modifier.
JSON parsing
public class Demo {public static void main (string[] args) throws Exception {Objectmapper mapper = new Object
Mapper (); When you deserialize the JSON, an unknown attribute causes deserialization to be interrupted, where we disable the unknown attribute to interrupt the deserialization feature,//Because, for example, there are 10 properties in JSON, and our Bean only has 2 attributes defined, and the other 8 properties will be ignored M
Apper.disable (deserializationfeature.fail_on_unknown_properties); Mapping from JSON to Java objects, the country object can be traversed after the lookup, the following traversal of some of the content, can explain the problem can be testjson Testjson = Mapper.readvalue ("{\ A\": \ "1\", \ "b\": \
"2\", \ "c\": \ "test\", "d\": \ "true\", \ "e\": \ "E\"} ", Testjson.class);
System.out.println ("A:" + Testjson.geta ());
System.out.println ("B:" + TESTJSON.GETB ());
System.out.println ("C:" + testjson.getc ());
System.out.println ("D:" + testjson.getd ());
} class Testjson {private Integer A;
Private Integer B;
Private String C;
Private Boolean D;
Public Integer Geta () {return A;
} public void SetA (Integer a) {this.a = A; Public Integer Getb () {return B;
} public void Setb (Integer b) {this.b = b;
Public String getc () {return C;
public void SetC (String c) {this.c = C;
Public Boolean getd () {return D;
public void setd (Boolean d) {this.d = D; }
}
Output:
a:1
b:2
c:test
d:true
When parsing, you can use the Typereference<t> class if you encounter a collection class.
public static <T> T json2obj (String jsonstr, typereference<t> typereference, string dateformat)
throws Exception {
Objectmapper objectmapper = Getobjectmapper ();
if (DateFormat!= null &&!dateformat.trim (). Equals ("")) {
Objectmapper.setdateformat (new SimpleDateFormat (DateFormat));
Return Objectmapper.readvalue (Jsonstr, typereference);
}
JSON generation
Import Com.fasterxml.jackson.annotation.JsonInclude;
Import Com.fasterxml.jackson.databind.ObjectMapper;
Import Com.fasterxml.jackson.databind.PropertyNamingStrategy;
Import Com.fasterxml.jackson.databind.SerializationFeature;
Import Com.fasterxml.jackson.databind.cfg.MapperConfig;
Import Com.fasterxml.jackson.databind.introspect.AnnotatedField;
Import Com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
Import java.io.IOException;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import java.util.*; public class Serializationexample { public static void main (string[] args) throws IOException, Parseexceptio n { Objectmapper mapper = new Objectmapper (); Album Album = new Al
Bum ("Kind of Blue");
album.setlinks (new string[]{"Link1", "Link2"});
list<string> songs = new Arraylist<string> (); Songs.add ("So What ");
Songs.add ("Flamenco Sketches");
Songs.add ("Freddie Freeloader");
album.setsongs (songs);
Artist Artist = new Artist ();
Artist.name = "Miles Davis";
SimpleDateFormat format = new SimpleDateFormat ("dd-mm-yyyy");
artist.birthdate = Format.parse ("26-05-1926");
album.setartist (artist);
Album.addmusician ("Miles Davis", "Trumpet, Band leader");
Album.addmusician ("Julian Adderley", "Alto saxophone");
Album.addmusician ("Paul Chambers", "double bass");
//Let JSON indent, readability better, generally used in the testing and development phase.
Mapper.configure (Serializationfeature.indent_output, true); //Let map key in natural order MAPPER.CONFIGure (Serializationfeature.order_map_entries_by_keys, true); //Date output format SimpleDateFormat OutputFormat = new SimpleDateFormat ("yyy
Y-mm-dd ");
Mapper.setdateformat (OutputFormat); ///By default, the Java class property name is the output JSON field name, but can be modified in annotations. If you don't want Java classes and JSON bindings /or can't modify Java classes, here's another way. You need to rewrite the following two methods, depending on whether the attribute is public or getter is public Mapper.setpropertynamingstrategy (new Propertynamingstrategy () { /** * @param config configuration in used:either serializationconfig or deserializationconfig, depending on whether meth OD is called during serialization or deserialization * @param field field Used to access property * @param defaultname Default name this would be us Ed For property in absence of custom strategy * @return & nbsp */ @Override Publi C String Nameforfield (mapperconfig<?> config, Annotatedfield field, String defaultname) { &NBSP ; if (Field.getfullname (). Equals ("Artist#name")) &NBSP ;
return "Artist-name";
return Super.nameforfield (config, field, defaultname); /** &N Bsp * @param config configuration in used:either serializationconfig or deserializationconfig, depending o N Whether method is called during serialization or deserialization &NBSP
* @param method method used to access. * @param defaultname Default name that would is used for property in Absen CE-Custom strategy * @return */ @Override public String NAMEF Orgettermethod (mapperconfig<?> config, Annotatedmethod method, String defaultname) { &N Bsp if (method.getannotated (). Getdeclaringclass (). Equals (Album.class) && defaultname.equals
("title"))
return "Album-title";
return Super.nameforgettermethod (config, method, defaultname);
} } &NBSp If the attribute has no value, then JSON is processed, the int type is 0,string type is null, the array is [], setting this attribute can ignore null attribute
Mapper.setserializationinclusion (JsonInclude.Include.NON_EMPTY);
Mapper.writevalue (System.out, album); } class Album { private String title; Private string[] links;
Private list<string> songs = new Arraylist<string> ();
Private Artist Artist;
Private map<string, string> musicians = new hashmap<string, string> (); Public Album (String title) { this.title = title; } Public String GetTitle () { return title: } public void setlinks (string[] links) { this.links = links; } public string[] Getlinks () { &nbs P
return links; } PUBlic void Setsongs (list<string> songs) { this.songs = songs; } &N Bsp Public list<string> getsongs () { return songs; : Public VO ID setartist (Artist Artist) { this.artist = Artist; } Public Art Ist getartist () { return artist / public map<string, string&
Gt
Getmusicians () { return collections.unmodifiablemap (musicians); }
public void Addmusician (string key, String value) { musicians.put (key, value); } class Artist { public String name: public Date birthdate; p
ublic int age;
public String hometown; public list<string> Awardswon = new arraylist<string> ();
}
Output:
{
"album-title": "Kind of Blue",
"links": ["Link1", "Link2"],
"songs": ["So What", "flamen Co sketches "," Freddie Freeloader "],
" artist ": {"
artist-name ":" Miles Davis ",
" birthdate ":" 192 6-05-26 ",
" age ": 0
},
" musicians ": {
" Julian Adderley ":" Alto saxophone ",
" Miles Davis ":" Trumpet, Band leader ",
" Paul Chambers ":" Double bass "
}
Streaming APIJackson provides a set of low-level APIs to parse the JSON string, which provides symbols for each JSON object. For example, ' {' Is the first object provided by the parser (Writestartobject ()), and the key-value pair is another individual object (WriteString (Key,value)) provided by the parser. These APIs are powerful, but require a lot of code. In most cases, the tree model and the data binding can replace the streaming API.
JSON parsing
public static void Main (string[] args) throws IOException {//from jsonfactory to obtain a Jsonparser instance jsonfactory FA
Ctory = new Jsonfactory (); Createparser has many kinds of overloads, you can see the API Jsonparser parser = Factory.createparser ("{\ title\": \ "free Music archive-albums\" , \ "message\": \ "test\", \ "errors\": [\ "Invalid or disabled api_key\"],\ "dataset\": [{\ "id\": \ "1\"},{\ "id\": \ "2\"}]} ")
; Parse the symbol until the end of the string while (!parser.isclosed ()) {//If necessary, this method will move along the stream until the next Jsontoken type Json is sufficient
Token Token = Parser.nexttoken ();
If it is the last Jsontoken, then the IF (token = null) break is ended; If Jsontoken is a jsontoken.field_name type and the current NAME is a dataset if (JsonToken.FIELD_NAME.equals (token) && datas
Et ". Equals (Parser.getcurrentname ())) {//Start parsing dateset, the first jsontoken must be Jsontoken.start_array" ["
token = Parser.nexttoken (); if (!
JsonToken.START_ARRAY.equals (token)) { Break
Each element of the//array is an object, so the next jsontoken is Jsontoken.start_object "{" token = Parser.nexttoken (); if (!
JsonToken.START_OBJECT.equals (token)) {break;
//Output ID field value while (true) {token = Parser.nexttoken ();
if (token = null) break; if (JsonToken.FIELD_NAME.equals (token) && "id". Equals (Parser.getcurrentname ()) {token =
Parser.nexttoken ();
System.out.println (Parser.gettext ()); }
}
}
}
}
JSON generation
public static void Main (string[] args) throws IOException {
Jsonfactory factory = new Jsonfactory ();
Jsongenerator generator = Factory.creategenerator (new Bufferedoutputstream (System.out));
Generator.writestartobject ();//{
generator.writefieldname ("title")
; Generator.writestring ("Free Music archive-albums");
Generator.writefieldname ("DataSet");
Generator.writestartarray ();//[
generator.writestartobject ();//{
Generator.writestringfield ("Album_ Title "," A.B.A.Y.A.M ");
Generator.writeendobject ()//}
Generator.writeendarray ();//]
generator.writeendobject ();/
/// Output {"title": "Free Music archive-albums", "DataSet": [{"Album_title": "A.B.A.Y.A.M"}]}
generator.close ();
}
Tree ModeIf you don't want to write a class for your JSON structure, tree mode is a good choice.
JSON generation
public static void Main (string[] args) throws IOException {
//Create a jsonnodefactory,false that provides all nodes does not create Decimalnode
Jsonnodefactory factory = new Jsonnodefactory (false);
Create Jsonfactory, output to console using the streaming API
jsonfactory jsonfactory = new Jsonfactory ();
Jsongenerator generator = Jsonfactory.creategenerator (System.out);
Objectmapper mapper = new Objectmapper ();
Create nodes and data, a Objectnode represents a Node object
objectnode Node1 = Factory.objectnode ();
Objectnode Node2 = Factory.objectnode ();
Node1.put ("A", "a");
Node1.put ("B", "B");
Node2.set ("C", Node1);
Root node
objectnode root = Factory.objectnode ();
Root.put ("root", "root");
Root.set ("Children", node2);
Mapper.writetree (generator, root);
Output {"Root": "Root", "children": {"C": {"a": "A", "B": "B"}}}
JSON parsing
public static void Main (string[] args) throws Exception {
Objectmapper mapper = new Objectmapper ();
Read JSON, the entire JSON as the root node
jsonnode node = mapper.readtree ("{\ root\": \ "root\", \ "children\": {\ "c\": {\ "a\": \ "A\", \ " B\ ": \" B\ "}}");
Look at the root node type
System.out.println ("node Jsonnodetype:" + node.getnodetype ());//object
// Is it a Containernode (array and Object nodes)
System.out.println ("node is Containernode?" + Node.iscontainernode ()) //true
//Get the direct child node name of all node nodes
iterator<string> fieldnames = Node.fieldnames ();
while (Fieldnames.hasnext ()) {
String fieldName = Fieldnames.next ();
System.out.println (FieldName + "");//root children
}
System.out.println (Node.get ("root"). Iscontainernode ());//false
}
SummaryThis is just the basic usage, and if anything else is useful, go ahead and add in.