Invalid character while converting from JSON to XML using jsonlib

南楼画角 提交于 2019-12-13 17:30:38

问题


I'm trying to convert a JSON string to XML using jsonlib in Java.

    JSONObject json = JSONObject.fromObject(jsonString); 
    XMLSerializer serializer = new XMLSerializer();
    String xml = serializer.write( json );  
    System.out.println(xml);

The error that I get is

    nu.xom.IllegalNameException: 0x24 is not a legal NCName character

The problem here is that I have some properties in my JSON that are invalid XML characters. eg. I have a property named "$t". The XMLSerializer throws the exception while trying to create a XML tag in this name because $ is not allowed in XML tag names. Is there any way in which I can override this XML well formedness check done by the serializer?


回答1:


First I'd suggest to add the language you are using (it is Java, right?).

You could override the method where it checks your XML tag name to do nothing.




回答2:


I took a look at the spec for the json-lib XMLSerializer and to my surprise it seems to have no option for serialising a JSON object whose keys are not valid XML names. If that's the case then I think you will need to find a different library.




回答3:


You could loop over json.keySet (recursively if necessary) and replace invalid keys with valid ones (using remove and add).



来源:https://stackoverflow.com/questions/7928535/invalid-character-while-converting-from-json-to-xml-using-jsonlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!