您的位置:首页 > 编程语言 > Java开发

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

2018-03-17 09:26 519 查看
<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();}}
代码样例参考了自动化测试REST API工具Wisdom RESTClienthttps://github.com/Wisdom-Projects/rest-client
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Wisdom RESTClient