<Dependency> <groupId>Commons-io</groupId> <Artifactid>Commons-io</Artifactid> <version>2.5</version></Dependency><Dependency> <groupId>Com.google.code.gson</groupId> <Artifactid>Gson</Artifactid> <version>2.8.0</version></Dependency>
Private StaticComparator<string>Getcomparator () {Comparator<String> C =NewComparator<string>() { Public intCompare (String O1, String O2) {returnO1.compareto (O2); } }; returnC; } Public Static voidsort (jsonelement e) {if(E.isjsonnull ()) {return; } if(E.isjsonprimitive ()) {return; } if(E.isjsonarray ()) {Jsonarray a=E.getasjsonarray (); for(Iterator<jsonelement> it =a.iterator (); It.hasnext ();) {Sort (It.next ()); } return; } if(E.isjsonobject ()) {Map<string, Jsonelement> TM =NewTreemap<string, jsonelement>(Getcomparator ()); for(Entry<string, jsonelement>en:e.getasjsonobject (). EntrySet ()) {Tm.put (En.getkey (), En.getvalue ()); } for(Entry<string, jsonelement>En:tm.entrySet ()) {e.getasjsonobject (). Remove (En.getkey ()); E.getasjsonobject (). Add (En.getkey (), En.getvalue ()); Sort (En.getvalue ()); } return; } } Public Static voidMain (string[] args) {Try{String JSON= Fileutils.readfiletostring (NewFile ("C://test//test.txt"), "UTF-8"); Gson g=NewGsonbuilder (). setprettyprinting (). Create (); Jsonparser P=NewJsonparser (); Jsonelement e=P.parse (JSON); Sort (e); System.out.println (G.tojson (e)); } Catch(Exception e) {e.printstacktrace (); } }
Sort json all nodes with Gson by key value key