![](/img/trans.png)
[英]How to convert a LinkedHashMap<String, List<Node>> into a JSONObject?
[英]How can I convert LinkedHashMap to JSONObject
ArrayList 條目,並且這個條目是 LinkedHashMap 類型的,我想把它轉換成 jsonOject 使用,我該怎么做呢?
for(Object entry : entries){
JSONObject entryToProcess = (JSONObject) entry;
}
嗨,這個轉換實用程序應該可以。 這里發生的是您調用 LinkedHashMap object 上的方法.getKeys()
來獲取所有密鑰。 然后對於每個鍵,您從 LinkedHashMap 檢索信息並將其放入 JSONObject
// Your input LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
// Providing general values for the test
linkedHashMap.put("First key", "First value");
linkedHashMap.put("Second key", "Second value");
linkedHashMap.put("Third key", "Third value");
// Initialization of the JSONObject
JSONObject jsonObject = new JSONObject();
// for-each key in the LinkedHashMap get the value and put both of
// them into the JSON
for (String key : linkedHashMap.keySet()) {
jsonObject.put(key, linkedHashMap.get(key));
}
你關心的部分應該是 for 循環。
干杯,
簡單的 JSONObject 構造函數就可以了
for(Object entry : entries){
JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
}
樣本:
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A",1);
linkedHashMap.put("some key","some value");
Map<String, String> someMap = new HashMap<>();
someMap.put("map-key-1","map-value-1");
someMap.put("map-key-2","map-value-2");
linkedHashMap.put("another key",someMap);
JSONObject jsonObject = new JSONObject(linkedHashMap);
System.out.println(jsonObject.toJSONString());
Output:
{
"another key": {
"map-key-1": "map-value-1",
"map-key-2": "map-value-2"
},
"A": 1,
"some key": "some value"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.