Java XStream 与 HashMap
我想使用 XStream 将 java 哈希转换为 json 哈希。我觉得这应该比看起来更容易。我正在寻找的是一种方法:
Map<String, String> map = new HashMap<String, String>();
map.put("first", "value1");
map.put("second", "value2");
成为
{'first' : 'value1', 'second' : 'value2' }
我已将其转换为一系列数组的关闭。
XStream xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.toXML(map);
我觉得
[["first", "value1"], ["second", "value2"]]
将 java 哈希转换为 json 哈希应该是直接的。我错过了什么吗?
I want to use XStream to convert a java hash to a json hash. I feel like this should be easier than it seems. What I'm looking for is a way to make:
Map<String, String> map = new HashMap<String, String>();
map.put("first", "value1");
map.put("second", "value2");
become
{'first' : 'value1', 'second' : 'value2' }
The closes I have converts it into a series of arrays.
XStream xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.toXML(map);
which becomes
[["first", "value1"], ["second", "value2"]]
I feel like converting a java hash to json hash should be straight forward. Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,XStream 首先也是最重要的设计目的是为了将 Java 对象编组和解编为 XML,而 JSON 只是事后的想法,它肯定具有最不优雅的支持。
技术问题是,由于 XStream 必须同时支持 XML 和 JSON 格式,因此 JSON 映射表示会受到影响,因为没有原生方法可以在 XML 中表示类似映射的结构。
The thing is that XStream is first and foremost designed to marshal and unmarshal Java objects to XML, JSON being just an afterthought, it most certainly has the least elegant support.
The technical problem being that as XStream must support both - XML and JSON formats, JSON map representation suffers, as there is no native way to represent a map-like structures in XML.
您可以尝试使用 json.org 中的“官方”java json 库。
呼叫:
You can try to use the "official" json lib for java from json.org.
Calling:
我在转换为 json 时遇到了类似的问题。我对这个问题的解决方案是在放入文件(在我的例子中是数据库)之前将字符串格式化为 Json。到目前为止,我想到的最有效的过程是在我的类中创建一个 toJson 函数,就像 toString 一样工作。
示例:
将对象数据输出字符串转换为 Json 格式
因此,您可以在填充地图时实现类似的过程。
I had similar issues when converting to jSon. My solution to this problem was to have the string already formatted to JSon before dropping into the file (in my case a database). The most efficient process I have come up with so far was to create a toJson function inside my classes to work just like toString.
Example:
Converts the objects data output string into Json format
So for you, implement a similar process while populating your map.