首页 > 解决方案 > 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!

标签: javajsonalgorithmiteration

解决方案


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.


推荐阅读