2011-01-26 17 views

答えて

3

要約:JSONにはプリミティブな順序付けされたマップタイプがないため、いいえです。

最初のステップは、JSON文字列のデコードが行われる限り、クライアントの要件を判断することです。 JSON仕様には順序付きマップタイプがないため、使用する表現を決める必要があります。選択は、クライアントのデコード要件によって異なります。

JSON文字列のデコードを完全に制御できる場合は、継承したイテレータの順番でシリアル化することが保証されているJSONライブラリを使用して、オブジェクトをマップに順番にエンコードするだけです。

これを保証できない場合は、自分で表現してください。 2つの単純な例は以下のとおりです。

交互リスト:

 
"[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; 
    } 
} 
関連する問題