The sort of jsonarray in Java, using Gson

Source: Internet
Author: User

Use Gson to parse the JSON string into a JSON object.

Code First: The following is the code inside the Main method

 PackageTestjava;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;ImportCom.google.gson.JsonParser;ImportCom.google.gson.JsonArray;ImportCom.google.gson.JsonObject; Public classTestjava { Public Static voidMain (string[] args) {//TODO auto-generated Method StubJsoaarraysort (); }     Public Static voidJsoaarraysort () {String arraydata= "[" + "{\" name\ ": \" tvs\ ", \" no\ ":" + 202 + ", \" length\ ":" + + "}," + "{\" name\ ": \" Tvc\ ", \ "No\": "+ 203 +", \ "length\": "+ + +"}, "+" {\ "name\": \ "wel\", \ "no\": "+ 345 +", \ "length\": "+ 35 +"}, "+" {\ "name\": \ "Sma\", \ "no\": "+ 678 +", \ "length\": "+ +"}, "+" {\ "name\": \ "Sma\", \ "No                \ ":" + 136 + ", \" length\ ":" + + + "}," + "{\" name\ ": \" cus\ ", \" no\ ":" + 257 + ", \" length\ ":" + 17 + "},"  + "{\" name\ ": \" and\ ", \" no\ ":" + 678 + ", \" length\ ":" + + "}," + "{\" name\ ": \" roo\ ", \" no\ ":" + 136 + ", \" length\ ":" + 56 + "}" + "]"; Jsonparser Parser=NewJsonparser (); Jsonarray Jsonarray=Parser.parse (arraydata). Getasjsonarray (); System.out.println ("Init jsonarray=" +jsonarray.tostring ()); Jsonarray Sort_jsonarray=NewJsonarray (); List<JsonObject> list =NewArraylist<jsonobject>(); Jsonobject Jsonobj=NULL;  for(inti = 0; I < jsonarray.size (); i++) {Jsonobj=(jsonobject) jsonarray.get (i);        List.add (Jsonobj); }        //The most central place here is the Sortcomparator class.//the parameters of which the method is constructed://Sortitem is an element in the Jsonarray to be sorted, here I choose to be name, can also choose no or length//SortType is a sort of type, there are three kinds of situations//1. The value of the sorted element corresponds to int, then sorttype = "int"; //2. The value of the ordered element corresponds to a string, then SortType = "string"; //3. The sorted elements correspond to other types, which are not sorted by default (can be extended later)//Sortdire is the direction of the sort, either ASC or DESC, the default is the original direction of the data (that is, there is no sort direction)String Sortitem = "Length"; String SortType= "int"; String Sortdire= "desc"; Collections.sort (list,New sortcomparator (Sortitem, SortType, Sortdire));  for(inti = 0; I < list.size (); i++) {Jsonobj=List.get (i);        Sort_jsonarray.add (Jsonobj); } System.out.println ("After sort_jsonarray=" +sort_jsonarray.tostring ()); }}

The following gives Sortcomparator.java

 PackageTestjava;ImportJava.util.Comparator;ImportCom.google.gson.JsonObject; Public classSortcomparatorImplementsComparator<jsonobject> {        PrivateString Sortitem; PrivateString SortType; PrivateString Sortdire;  Publicsortcomparator (String Sortitem, String SortType, String sortdire) { This. Sortitem =Sortitem;  This. SortType =SortType;  This. Sortdire =Sortdire; } @Override Public intCompare (Jsonobject O1, Jsonobject O2) {String value1=o1.getasjsonobject (). Get (Sortitem). getasstring (); String value2=o2.getasjsonobject (). Get (Sortitem). getasstring (); if("int". Equalsignorecase ( This. SortType)) {//int Sort            intInt1 =Integer.parseint (value1); intInt2 =Integer.parseint (value2); if("ASC". Equalsignorecase ( This. Sortdire)) {                returnInt1-Int2; } Else if("desc". Equalsignorecase ( This. Sortdire)) {                returnInt2-int1; } Else {                return0; }              } Else if("string". Equalsignorecase ( This. SortType)) {//string Sort            if("ASC". Equalsignorecase ( This. Sortdire)) {                returnValue1.compareto (value2); } Else if("desc". Equalsignorecase ( This. Sortdire)) {                returnValue2.compareto (value1); } Else {                return0; }        } Else{//Nothing sort            return0; }            }}

Results of the test:

the initial values of the Jsonarray are as follows: [{"name": "TVS", "no": 202, "Length": +}, {"name": "TVC", "No": 203, "Length": +}, {"name": " Wel "," no ": 345," Length ": +}, {" name ":" SMA "," no ": 678," Length ":", "" SMA "," no ": 136," Length ": +}, {" name ":" Cus "," no ": 257," Length ": +}, {" name ":" and "," no ": 678," Length ": +} , {"Name": "Roo", "No": 136, "Length":];
 The following is a small arrival sorted by the Name element: sortcomparator ("Name", "string", "ASC"  )  after Sort_jsonarray  =[{  "name": "and", "no": 678, "Length": 16}, { "name": "Cus", "no": 257, "Length" : 17 "Name": "Roo", "No": 136, "Length": 56}, {  "name": "SMA", "no": 678, "Length": 45}, { "name": "SMA", "no": 136, "Length" : 15 "Name": "TVC", "No": 203, "Length": 14}, {  "name": "TVS", "no": 202, "Length": 23}, { "name": "Wel", "no": 345, "Length" : 35 
 The following is the order of the name elements from large to small:  Sortcomparator ("Name", "string", "desc"  )  after Sort_jsonarray  =[{  "name": "Wel", "no": 345, "Length": 35}, { "name": "TVS", "no": 202, "Length" : 23 "Name": "TVC", "No": 203, "Length": 14}, {
      "name": "SMA", "no": 678, "Length": 45}, { "name": "SMA", "no": 136, "Length": 15  "Name": "Roo", "No": 136, "Length": 56}, {  "name": "Cus", "no": 257, "Length": 17}, { "name": "and", "No": 678, "Length" : 16 
 The following is ordered from small to large by the Length element: sortcomparator ("Length", "int", "ASC"  )  after Sort_jsonarray  =[{  "name": "TVC", "No": 203, "Length": 14}, { "name": "Sma", "no": 136, "Length" : 15 "Name": "and", "No": 678, "Length": 16}, {
      "name": "Cus", "no": 257, "Length": 17}, { "name": "TVS", "no": 202, "Length": 23  "Name": "Wel", "No": 345, "Length": 35}, {  "name": "Sma", "no": 678, "Length": 45}, { "name": "Roo", "no": 136, "Length" : 56 
The following are sorted by the Length element from large to small: sortcomparator ("Length", "int", "desc")after Sort_jsonarray=[    {"Name": "Roo", "No": 136, "Length":.    {"name": "Sma", "no": 678, "Length": "{"},    {"name": "Wel", "no": 345, "Length": +},    {" Name ":" "TVS", "no": 202, "Length": +},    {"name": "Cus", "no": 257, "Length": +},    {"name ":" and "," No ": 678," Length ": +},    {" name ":" Sma "," no ": 136," Length ":},    {" name ":" TVC "," No ": 203," Length ": +}]

The sort of jsonarray in Java, using Gson

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.