Invalid character while converting from JSON to XML using jsonlib

4k Views Asked by At

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?

3

There are 3 best solutions below

0
On

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.

0
On

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.

0
On

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