Java用Gson按照键值key排序json所有节点

<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();
        }
    }

 

posted @ 2018-02-12 16:02  千里驹  阅读(3330)  评论(1编辑  收藏  举报