我正在创建一个JSON对象,我在其中添加一个键和一个数组值.key和value的值来自TreeSet,它具有排序形式的数据.但是,当我在我的json对象中插入数据时,它是随机存储的,没有任何顺序.这是我目前的json对象:
{
"SPAIN":["SPAIN","this"],
"TAIWAN":["TAIWAN","this"],
"NORWAY":["NORWAY","this"],
"LATIN_AMERICA":["LATIN_AMERICA","this"]
}
Run Code Online (Sandbox Code Playgroud)
我的代码是:
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);
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以将数据存储到while循环内部的json对象中吗?
即使这篇文章很老,我认为没有GSON也值得发布一个替代方案:
首先将您的密钥存储在ArrayList中,然后对其进行排序并遍历密钥的ArrayList:
Iterator<String> it= MyTreeSet.iterator();
ArrayList<String>keys = new ArrayList();
while (it.hasNext()) {
keys.add(it.next());
}
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
String country = keys.get(i);
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this");
jsonObj.put(country, jsonArray);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17111 次 |
| 最近记录: |