Java to JSON:
1 PackageJson.jackson;2 3 ImportBean. User;4 ImportCom.fasterxml.jackson.databind.ObjectMapper;5 6 ImportJava.io.File;7 ImportJava.util.Map;8 9 /**Ten * Jackson–java to JSON One * Functions: JSON and Java object, map and other types of conversion, JSON file reading and writing, etc. A * Dependent packages: Jackson-databind-2.8.11.1.jar, Jackson-core-2.8.10.jar, Jackson-annotations-2.8.0.jar - * Https://github.com/FasterXML/jackson-databind - */ the Public classJavatojson { - Public Static voidMain (string[] ARS)throwsException { -User User =NewUser ("Tom", "the most street"); -Objectmapper Objectmapper =NewObjectmapper (); + - //Java object to JSON, also supports bytes +String JSON =objectmapper.writevalueasstring (user); ASystem.out.println ("Java object to JSON:" +JSON); at - //JSON to Java object -User User2 = Objectmapper.readvalue (JSON, user.class); -SYSTEM.OUT.PRINTLN ("JSON to Java object" +user2); - - //Read the file inString Jsonfilepath = "Src/main/java/json/jackson/jsonreader.json"; -User User3 = Objectmapper.readvalue (NewFile (Jsonfilepath), User.class); toSYSTEM.OUT.PRINTLN ("Read JSON file:" +user3); + //Write a file -Objectmapper.writevalue (NewFile (Jsonfilepath), user3); the * //JSON to map, also supports list $Map map = Objectmapper.readvalue (JSON, map.class);Panax NotoginsengSYSTEM.OUT.PRINTLN ("JSON to map:" +map); - the //map to JSON string, supports all types of Go-string +String Json2 =objectmapper.writevalueasstring (map); ASYSTEM.OUT.PRINTLN ("Map to JSON:" +json2); the + } -}
Jsonnode:
1 PackageJson.jackson;2 3 ImportCom.fasterxml.jackson.databind.JsonNode;4 ImportCom.fasterxml.jackson.databind.ObjectMapper;5 6 ImportJava.io.File;7 Importjava.util.List;8 9 /**Ten * Jsonnode One * Handle complex JSON, return multiple objects case A * Read complex JSON from file, find corresponding value value according to key - * Dependent packages: Jackson-databind-2.8.11.1.jar, Jackson-core-2.8.10.jar, Jackson-annotations-2.8.0.jar - * Https://github.com/FasterXML/jackson-databind the */ - Public classJsontreedemo { - Public Static voidMain (string[] ARS)throwsException { -Objectmapper Objectmapper =NewObjectmapper (); +String Jsonfilepath = "Src/main/java/json/jackson/json2.json"; - //support for multiple objects in tree form: Supports reading multiple types +Jsonnode Jsonnode = Objectmapper.readtree (NewFile (Jsonfilepath)); ASystem.out.println ("Jsonnode:" +jsonnode); at //query multiple values based on key, return list -list<jsonnode> list = jsonnode.findvalues ("name"); -System.out.println ("Values:" +list); - - //querying a single value by key -String channel = Jsonnode.get ("channel"). Astext (); inSYSTEM.OUT.PRINTLN ("Query the value of channel:" +channel); - } to}
Java JSON operation (Jackson)