如何将SimpleOrderedMap转换为JSON字符串或JSON对象?

发布于 2024-10-14 17:37:32 字数 23 浏览 2 评论 0原文

有没有标准的方法可以做到这一点?

Is there any standard way to do so?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-10-21 17:37:32

简而言之:不,因为 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());
}

In short: no, because JSON doesn't have a primitive ordered map type.

The first step is to determine the requirements of your client, as far as decoding the JSON string goes. Since the JSON specification doesn't have an ordered map type, you'll have to decide on a representation to use. The choice you make will depend on the decoding requirements of your client.

If you have full control over the decoding of the JSON string, you can simply encode the object into a map in order, using a JSON library that is guaranteed to serialize things in the order of an iterator that you pass in.

If you can't guarantee this, you should come up with a representation on your own. Two simple examples are:

An alternating list:

"[key1, value1, key2, value2]"

A list of key/value entry objects:

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

Once you've come up with this representation, it's easy to write a simple function that loops over your SimpleOrderedMap. For example :

JSONArray jarray = new JSONArray();
for(Map.Entry e : simpleOrderedMap) {
    jarray.put(e.key());
    jarray.put(e.value());
}
歌枕肩 2024-10-21 17:37:32

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;
    }
}

Java version:

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;
    }
}
陌路终见情 2024-10-21 17:37:32

简单地向映射添加字段是行不通的,因为可能存在复杂的对象(不会序列化为 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
}

Simple adding fields to map won't work, as complex objects (which does not serialize to JSON) could be there.

Here's a groovy code that does it.

 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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文