我需要按照插入的顺序使用键/值对,所以我选择在LinkedHashMap
上使用HashMap
。但我需要将LinkedHashMap
转换为JSON字符串,其中LinkedHashMap
中的顺序保留在字符串中。
但目前我通过以下方式实现:
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONObject;
public class cdf {
public static void main(String[] args) {
Map<String,String > myLinkedHashMap = new LinkedHashMap<String, String>();
myLinkedHashMap.put("1","first");
myLinkedHashMap.put("2","second");
myLinkedHashMap.put("3","third");
JSONObject json = new JSONObject(myLinkedHashMap);
System.out.println(json.toString());
}
}
输出是:
{"3":"third","2":"second","1":"first"} .
但我希望它按插入键的顺序,如下所示:
{"1":"first","2":"second","3":"third"}
一旦我将LinkedHashMap
转换为JSON,它就会失去它的顺序(显然JSON没有顺序的概念)因此字符串也是乱序的。现在,如何生成一个与LinkedHashMap
相同的JSON字符串?
如果你的朋友,Gson。这会将有序映射打印为有序的JSON字符串。
如果要保留插入顺序,请使用LinkedHashMap
。
我使用了最新版本的Gson(2.8.5),您可以通过本文底部的以下选项下载它。
import java.util.*;
import com.google.gson.Gson;
public class OrderedJson {
public static void main(String[] args) {
// Create a new ordered map.
Map<String,String> myLinkedHashMap = new LinkedHashMap<String, String>();
// Add items, in-order, to the map.
myLinkedHashMap.put("1", "first");
myLinkedHashMap.put("2", "second");
myLinkedHashMap.put("3", "third");
// Instantiate a new Gson instance.
Gson gson = new Gson();
// Convert the ordered map into an ordered string.
String json = gson.toJson(myLinkedHashMap, LinkedHashMap.class);
// Print ordered string.
System.out.println(json); // {"1":"first","2":"second","3":"third"}
}
}
如果您希望始终将项目插入正确的位置,请使用TreeMap
。
import java.util.*;
import com.google.gson.Gson;
public class OrderedJson {
public static void main(String[] args) {
// Create a new ordered map.
Map<String,String> myTreeHashMap = new TreeMap<String, String>();
// Add items, in any order, to the map.
myTreeHashMap.put("3", "third");
myTreeHashMap.put("1", "first");
myTreeHashMap.put("2", "second");
// Instantiate a new Gson instance.
Gson gson = new Gson();
// Convert the ordered map into an ordered string.
String json = gson.toJson(myTreeHashMap, TreeMap.class);
// Print ordered string.
System.out.println(json); // {"1":"first","2":"second","3":"third"}
}
}
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
compile 'com.google.code.gson:gson:2.8.5'
或者您可以访问Maven Central获取更多下载选项。
JSONObject
暗示使用org.json
库。不要那样做;它是旧的原型,有更好的选择,如杰克逊和GSON。有杰克逊,你只需使用:
String json = new ObjectMapper().writeValueAsString(myLinkedHashMap);
并使用Map使用的任何遍历顺序获取带有条目的JSON字符串。
由于linkedhashmap params而不接受插入顺序的JSON都是字符串。像下面提到的代码一样将第一个参数改为Integer是没关系的:
Map<Integer,String > myLinkedHashMap = new LinkedHashMap<>();
myLinkedHashMap.put(1,"first");
myLinkedHashMap.put(2,"second");
myLinkedHashMap.put(3,"third");
System.out.println(myLinkedHashMap);
JSONObject json = new JSONObject(myLinkedHashMap);
System.out.println(json.toString());
按字母顺序排序,这是杰克逊2的正确方法。*:
Map<String, String> myLinkedHashMap = new LinkedHashMap<String, String>();
myLinkedHashMap.put("1", "first");
myLinkedHashMap.put("2", "second");
myLinkedHashMap.put("3", "third");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
try {
System.out.println(mapper.writeValueAsString(myLinkedHashMap));
//prints {"1":"first","2":"second","3":"third"}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
我遇到了同样的问题。我不得不使用这个特殊的库,第一个元素必须是键“$ type”。这是我的决定:
import org.json.JSONObject;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
class TypedJSONObject extends JSONObject {
private static final String KEY = "$type";
@Override
public Set<Map.Entry<String, Object>> entrySet() {
Set<Map.Entry<String, Object>> superSet = super.entrySet();
Set<Map.Entry<String, Object>> returnSet = new LinkedHashSet<>();
HashMap<String, Object> map = new HashMap<>();
for (Map.Entry<String, Object> entry : superSet) {
if (entry.getKey().equals(KEY)) {
map.put(KEY, entry.getValue());
break;
}
}
Set<Map.Entry<String, Object>> entries = map.entrySet();
returnSet.addAll(entries);
returnSet.addAll(superSet);
return returnSet;
}
}
如您所见,我重写方法entrySet,用于方法toString
为有序对创建JsonArray ...
JSONArray orderedJson=new JSONArray();
Iterator iterator= ;
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry)iteratornext();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
JSONObject tmpJson=new JSONObject ();
tmpJson.put(me.getKey(),me.getValue());//add key/value to tmpjson
orderedJson.add(tmpJson);//add tmpjson to orderedJson
}