0

そうするための標準的な方法はありますか?

4

3 に答える 3

3

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

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

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

これを保証できない場合は、自分で表現を考え出す必要があります。2 つの簡単な例を次に示します。

交互のリスト:

「[キー1、値1、キー2、値2]」

キー/値エントリ オブジェクトのリスト:

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

この表現を思いついたら、SimpleOrderedMap をループする単純な関数を簡単に作成できます。例えば ​​:

JSONArray jarray = 新しい JSONArray();
for(Map.Entry e : simpleOrderedMap) {
    jarray.put(e.key());
    jarray.put(e.value());
}
于 2011-01-26T01:26:54.467 に答える
2

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;
    }
}
于 2016-05-18T21:32:23.463 に答える
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
}
于 2011-01-27T08:00:48.227 に答える