java - How to convert an XML structured-like object to a JSON string in Java?
问题描述
So I have an XML structured object (Java) and need some help to convert it to a JSON string without using any library and in an iterative way.
E.g
<root>
<a/>
<b/>
<a/>
<a>
<c/>
<a/>
<d>
...
</d>
<root/>
Which could be represented in a class (Java) like:
class Element {
String name; (root)
List<Element> childs; (a, b, a, a, d)(i.e. direct childs)
}
And should be in JSON:
{
"root":{
"a":[
{},
{},
{
"c":{}
}
],
"b": {},
"d": {
...
}
}
}
The depth can be infinite (not really but it can be really deep) and the JSON string does not need to be indented or keep the same order, it just need to be valid JSON as the example. The difficult thing (except to make it an iterative solution) is that several elements with the same name at the same level should be an array in the JSON since JSON does not like it when there are elements with the same name at the same level.
Edit: I'm not looking for a library, as I stated earlier. Besides, the library many of you mentioned uses recursion which is not what I want either. And I'm not converting an actual XML, instead it's an XML structured-like object, i.e. it can be nested with child elements with the same name at the same level, different depths etc. Like in the example. Thanks though!
解决方案
I'm not sure what you mean by "without using any library", and I'm not sure what you mean by "iterative" or "optimal".
XML and JSON have different data models, and there's no perfect optimal way of converting one to the other. There are many different libraries that do a reasonably good job, but they all have limitations. One of the difficulties you mention is XML elements that have multiple children with the same name (like a <div>
containing multiple <p>
elements). At first sight it ertermakes sense to turn the <p>
elements into a array. But then what do you do if there's a <div>
that only has one <p>
child? Every converter finds different answers to this problem, and none of them is perfect.
Saying you don't want to use any library implies you want to write your own converter. That's not a crazy idea, because you can then adapt the conversion rules to the nature of your particular data model. And you can then decide what "optimal" means for you.
But your question really seems to be "please tell me what conversion rules I should apply", and the only answer to that is that there are no conversion rules that work well for everyone.
推荐阅读
- iis - 如何对在定期回收的农场中运行的具体异常进行 Web 应用程序的小型转储?
- swift - 我需要将参数数量传递给与变量数组计数等效的函数
- python - 如何使用无头渲染在 ubuntu 14.04 上安装 Pyrender?
- indexing - Neo4j - 我如何决定索引什么?
- php - 在删除重复项时合并两个多维数组,依赖于它们的特定元素
- genexus - 如何修复 Genexus 16 U 4 找不到符号 createMasterPage?
- reactjs - 通过 react/axios 从 spring 获取请求中查看 pdf
- vue.js - 如何计算此特定对象中的元素数量
- php - PHP 将对象从页面传递到套接字
- android - 自定义 html 视图以支持 android textview 中的图像。Web 视图在 base64 图像中加载非常慢