2011-01-26 194 views

回答

3

總之:不,因爲JSON沒有原始的有序地圖類型。

只要解碼JSON字符串,第一步就是確定客戶端的需求。由於JSON規範沒有有序的地圖類型,因此您必須決定要使用的表示形式。您所做的選擇取決於客戶的解碼要求。

如果您完全控制JSON字符串的解碼,那麼您可以簡單地按照順序將對象編碼爲地圖,使用JSON庫,保證按照您傳入的迭代器的順序對事物進行序列化。

如果你不能保證這一點,你應該自己想出一個代表。兩個簡單的例子是:

的交流清單:

 
"[key1, value1, key2, value2]" 

鍵/值項的對象列表:

 
"[{key: key1, val:value1}, {key: key2, val:value2}]" 

一旦你想出這個表現,很容易寫一個遍歷SimpleOrderedMap的簡單函數。例如:

 
JSONArray jarray = new JSONArray(); 
for(Map.Entry e : simpleOrderedMap) { 
    jarray.put(e.key()); 
    jarray.put(e.value()); 
} 
0

由於複雜的對象(不會序列化爲JSON)可能存在,所以向映射添加簡單字段將不起作用。

這是一個很好的代碼。

protected static toMap(entry){ 
    def response 
    if(entry instanceof SolrDocumentList){ 
     def docs = [] 
     response = [numFound:entry.numFound, maxScore:entry.maxScore, start:entry.start, docs:docs] 
     entry.each { 
      docs << toMap(it) 
     } 
    } else 
    if(entry instanceof List){ 
     response = [] 
     entry.each { 
      response << toMap(it) 
     } 
    } else 
    if(entry instanceof Iterable){ 
     response = [:] 
     entry.each { 
      if(it instanceof Map.Entry) 
    response.put(it.key, toMap(it.value)) 
      else 
      response.put(entry.hashCode(), toMap(it)) 
     } 
    } else 
if (entry instanceof Map){ 
     response = [:] 
     entry.each { 
      if(it instanceof Map.Entry) 
    response.put(it.key, toMap(it.value)) 
      else 
      response.put(entry.hashCode(), toMap(it)) 
     } 
    } else { 
     response = entry 
    } 
    return response 
} 
1

Java版本:

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Map.Entry; 

import org.apache.solr.common.util.NamedList; 

public class SolrMapConverter { 

    @SuppressWarnings({ "unchecked", "rawtypes" }) 
    public static Object toMap(Object entry) { 
     Object response = null; 
     if (entry instanceof NamedList) { 
      response = new HashMap<>(); 
      NamedList lst = (NamedList) entry; 
      for (int i = 0; i < lst.size(); i++) { 
       ((Map) response).put(lst.getName(i), toMap(lst.getVal(i))); 
      } 
     } else if (entry instanceof Iterable) { 
      response = new ArrayList<>(); 
      for (Object e : (Iterable) entry) { 
       ((ArrayList<Object>) response).add(toMap(e)); 
      } 
     } else if (entry instanceof Map) { 
      response = new HashMap<>(); 
      for (Entry<String, ?> e : ((Map<String, ?>) entry).entrySet()) { 
       ((Map) response).put(e.getKey(), toMap(e.getValue())); 
      } 
     } else { 
      return entry; 
     } 
     return response; 
    } 
} 
相關問題