Add Jackson Dependency:
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-coreCompile group: ' Com.fasterxml.jackson.core ', Name: ' Jackson-core ', version: ' 2.8.2 '//https://mvnrepository.com/ Artifact/com.fasterxml.jackson.core/jackson-databindCompile group: ' Com.fasterxml.jackson.core ', Name: ' Jackson-databind ', version: ' 2.8.2 '//https://mvnrepository.com/artifact/com.fasterxml.jackson.core/ Jackson-annotationsCompile group: ' Com.fasterxml.jackson.core ', Name: ' Jackson-annotations ', version: ' 2.8.2 '
See Fasterxml also thought to find the wrong reliance, also thought and Com.alibaba:fastjson This has what connection, thought is a person called Jack wrote. There are three dependencies, and it's natural to take it for granted that most frameworks rely on Jackson to handle JSON conversions.
Pojo serialized as JSON string:
Prepare a Pojo:
@JsonIgnoreProperties (Ignoreunknown =true)classUserImplementsSerializable {Private Static Final LongSerialversionuid = -5952920972581467417l; PrivateString name; PublicUser () {} PublicUser (String name) { This. Name =name; } PublicString GetName () {returnname; } @Override PublicString toString () {return"user{" + "name=" + Name + '} '; }}
Convert to Jason string by write:
String expected = "{\" name\ ": \" test\ "}"= mapper.writevalueasstring (new User ("Test")); Assert.assertequals (expected, test);
Parse JSON string as Pojo object by read:
User user = Mapper.readvalue (expected, user. Class); Assert.assertequals ("Test", User.getname ());
Jsonarray converted to array arrays:
String expected = "[{\" name\ ": \" ryan\ "},{\" name\ ": \" test\ "},{\" name\ ": \" Leslie\ "}]"= Mapper.gettypefactory (). Constructarraytype (User. Class= Mapper.readvalue (expected, arraytype); Assert.assertequals ("Ryan", Users[0].getname ());
Jsonarray converted to list<> generics:
Expected= "[{\" a\ ": 12},{\" b\ ": 23},{\" name\ ": \" ryan\ "}]"= Mapper.gettypefactory (). Constructcollectiontype (ArrayList. Class, User. class ); // The sieze of the list is Dependon the str JSON length although the JSON content are not the POJO type maybe List<user> userlist = Mapper.readvalue (expected, listtype); Assert.assertequals (3, Userlist.size ()); Assert.assertnull (Userlist.get (0). GetName ()); Assert.assertequals ("Ryan", Userlist.get (2). GetName ());
Jackson By default converts an object to Linkedhashmap:
String expected = "[{\" name\ ": \" ryan\ "},{\" name\ ": \" test\ "},{\" name\ ": \" Leslie\ "}]"= Mapper.readvalue ( Expected, ArrayList. class = arraylist.get (0instanceof linkedhashmap);
Jackson simple to use, object to Json,json to object, JSON to list