如何基于Key对JSON对象进行排序?

编程入门 行业动态 更新时间:2024-10-09 14:26:08
本文介绍了如何基于Key对JSON对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建一个JSON对象,我在其中添加一个键和一个数组值。 key和value的值来自TreeSet,它具有排序形式的数据。但是,当我在我的json对象中插入数据时,它是随机存储的,没有任何顺序。 这是我目前的json对象:

I am creating a JSON object in which i am adding a key and a value which is an array. The value for both key and value comes from a TreeSet which has data in sorted form. However, when I insert data in my json object, it is stored randomly without any order. This is my json object currently:

{ "SPAIN":["SPAIN","this"], "TAIWAN":["TAIWAN","this"], "NORWAY":["NORWAY","this"], "LATIN_AMERICA":["LATIN_AMERICA","this"] }

我的代码是:

Iterator<String> it= MyTreeSet.iterator(); while (it.hasNext()) { String country = it.next(); System.out.println("----country"+country); JSONArray jsonArray = new JSONArray(); jsonArray.put(country); jsonArray.put("this); jsonObj.put(country, jsonArray); }

我有什么方法可以将数据存储到while循环内部的json对象中吗?

Is there any way I can store the data into my json object inside the while loop itself?

推荐答案

适用于Google Gson API。尝试一下。

It works with Google Gson API. Try it out.

try{ TreeSet<String> MyTreeSet = new TreeSet<String>(); MyTreeSet.add("SPAIN"); MyTreeSet.add("TAIWNA"); MyTreeSet.add("INDIA"); MyTreeSet.add("JAPAN"); System.out.println(MyTreeSet); Iterator<String> it= MyTreeSet.iterator(); JsonObject gsonObj = new JsonObject(); JSONObject jsonObj = new JSONObject(); while (it.hasNext()) { String country = it.next(); System.out.println("----country"+country); JSONArray jsonArray = new JSONArray(); jsonArray.put(country); jsonArray.put("this"); jsonObj.put(country, jsonArray); JsonArray gsonArray = new JsonArray(); gsonArray.add(new JsonPrimitive("country")); gsonArray.add(new JsonPrimitive("this")); gsonObj.add(country, gsonArray); } System.out.println(gsonObj.toString()); System.out.println(jsonObj.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }

更多推荐

如何基于Key对JSON对象进行排序?

本文发布于:2023-11-26 09:11:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Key   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!