有没有任何标准的方法来做到这一点?如何将SimpleOrderedMap转换为JSON字符串或JSON对象?
0
A
回答
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;
}
}
相关问题
- 1. 将字符串转换为JSON对象
- 2. 将字符串转换为json对象
- 3. 将JSON对象转换为字符串
- 4. 将json对象转换为字符串
- 5. 将字符串转换为JSON对象
- 6. 将json字符串转换为对象
- 7. 如何将JSON字符串转换为JSON对象?
- 8. 如何将字符串json转换为JSON对象
- 9. 如何在PHP中将json字符串转换为json对象?
- 10. 如何使用JavaScript将JSON字符串转换为JSON对象?
- 11. 当将json对象转换为字符串或字节时,Json对象包含转换为“\ n”的换行符
- 12. 转换JSON字符串JSON对象C#
- 13. 如何将JSON对象转换为对应的字符串
- 14. 将“已转换”的对象字符串转换为JSON或对象
- 15. 字符串转换为JSON对象C#
- 16. 将JSON字符串转换为Java对象或HashMap
- 17. 将json字符串转换为javascript变量或对象
- 18. 将json字符串转换为json对象?
- 19. 将JSON字符串转换为具有空值的JSON对象
- 20. javascript将JSON字符串转换为JSON对象
- 21. 将json字符串转换为muler中的json对象
- 22. 将JSON字符串转换为JSON对象
- 23. 将JSON字符串转换为Scala中的JSON对象
- 24. 将JSON对象转换为序列化的JSON字符串
- 25. 如何将JSON转换为字符串?
- 26. 如何将字符串转换为Json
- 27. 如何将字符串转换为json
- 28. 如何将此字符串转换为JSON对象?
- 29. 如何将JSON字符串转换为JS对象?
- 30. 如何将下面的json字符串转换为java对象?