1. 程式人生 > >用Gson按照鍵值key排序json所有節點

用Gson按照鍵值key排序json所有節點

span urn ive exception tree 8.0 ring creat entryset

<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 static Comparator<String> getComparator()
    {
        Comparator<String> c = new Comparator<String>()
        {
            public int compare(String o1, String o2)
            {
                return o1.compareTo(o2);
            }
        };

        
return c; } public static void sort(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 = new TreeMap<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 void main(String[] args) { try { String json = FileUtils.readFileToString(new File("C://test//test.txt"), "UTF-8"); Gson g = new GsonBuilder().setPrettyPrinting().create(); JsonParser p = new JsonParser(); JsonElement e = p.parse(json); sort(e); System.out.println(g.toJson(e)); } catch(Exception e) { e.printStackTrace(); } }

用Gson按照鍵值key排序json所有節點