码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-02-12 18:42:55      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:tin   tac   map   tty   []   void   rac   try   prim   

<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所有节点

标签:tin   tac   map   tty   []   void   rac   try   prim   

原文地址:https://www.cnblogs.com/witpool/p/8444795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!