将嵌套XML转换为JSON

时间:2016-07-22 11:54:43

标签: json xml parsing xstream

我需要编写一个将XML转换为Json的库。我一直在尝试并使用其中一个答案的帮助,我可以这样做:

xml的示例:

<website>
<created-at  type="datetime"> 2010-02-17T14:36:26-08:00</created-at>
<id  type=

"integer"> 12</id>
    <primary-host-id  type="integer"  nil="true"></primary-host-id>
    <suspended  type="boolean"> false</suspended>
    <hosts  type="array">
<host>
    <id  type="integer"> 12</id>
    <name> example.viviti.com</name>
</host>
<host>
    <id  type="integer"> 12</id>
    <name> example.viviti.com</name>
    </host>
</hosts>
    <ip-address> 127.0.0.1</ip-address>
    </website>

所以,我写了一个产生这个json的代码,

{ip-address= 127.0.0.1, hosts={host=[{name= example.viviti.com, id= 12}, {name= example.viviti.com, id= 12}]}, created-at= 2010-02-17T14:36:26-08:00, id= 12, primary-host-id=, suspended= false}

它将“host”作为数组,但我需要的是“hosts”作为数组。 所以,预期的json会是这样的:

    {
  "website":{
     "created-at":"2010-02-17T14:36:26-08:00",
     "id":"12",
     "suspended":"false",
     "ip-primary-host-id":"",
     "ip-address":"127.0.0.1",
     "hosts":[
        {
           "host":{
              "name":"example.viviti.com",
              "id":"12"
           }
        },
        {
           "host":{
              "name":"example1.viviti.com",
              "id":"13"
           }
        }
     ]
  }
}

这是我现有的代码:

public static void main(String[] args) throws Exception
    {


        XStream magicApi = new XStream();
        magicApi.registerConverter(new MapEntryConverter());
        magicApi.alias("website", Map.class);



        Map extractedMap = (Map) magicApi.fromXML(RESPONSE);
        System.out.println(extractedMap);

    }

    public static class MapEntryConverter implements Converter
    {

        public boolean canConvert(Class clazz)
        {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context)
        {

            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet())
            {
                Map.Entry entry = (Map.Entry) obj;
                writer.startNode(entry.getKey().toString());
                Object val = entry.getValue();
                if (null != val)
                {
                    writer.setValue(val.toString());
                }
                writer.endNode();
            }

        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context)
        {

            Map<String, Object> map = new HashMap<String, Object>();

            while (reader.hasMoreChildren())
            {
                reader.moveDown();

                String key = reader.getNodeName();

                if(reader.hasMoreChildren())
                {
//                    reader.moveDown();

                    Object interim = unmarshal(reader, context);
                    if(!map.containsKey(key))
                    {
                        map.put(key, interim);
                    }
                    else
                    {
                        List list = new ArrayList();
                        list.add(map.get(key));
                        list.add(interim);
                        map.put(key,list);
                    }
//                    reader.moveUp();
                }
                else
                {
                    String value = reader.getValue();
                    map.put(key, value);
                }

                reader.moveUp();
            }

            return map;
        }

    }

另外,我不想在json中使用XML命名空间。 感谢帮助。

1 个答案:

答案 0 :(得分:0)

为什么不使用JSONObject。使用此对象生成JSON要简单得多。这将为您节省大量的LOC。

public class Main {

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(YOUR_XML_STRING);
            System.out.println(xmlJSONObj.toString());
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

输出

{
    "website": {
        "created-at": {
            "-type": "datetime",
            "#text": " 2010-02-17T14:36:26-08:00"
        },
        "id": {
            "-type": "integer",
            "#text": " 12"
        },
        "primary-host-id": {
            "-type": "integer",
            "-nil": "true"
        },
        "suspended": {
            "-type": "boolean",
            "#text": " false"
        },
        "hosts": {
            "-type": "array",
            "host": [
                {
                    "id": {
                        "-type": "integer",
                        "#text": " 12"
                    },
                    "name": " example.viviti.com"
                },
                {
                    "id": {
                        "-type": "integer",
                        "#text": " 12"
                    },
                    "name": " example.viviti.com"
                }
            ]
        },
        "ip-address": " 127.0.0.1"
    }
}

more info...