tags:

views:

43

answers:

2

I want to store a string which itself is an XML string as a property of an JSON object , what's the reliable and proper way of dong this? Should I first encode the XML data into BASE64 first prior saving it to an JSON object, due to the fact that JSON does not support binary data?

Example of data I want to store:

{ 
"string1" : "<xml>...moderately complex XML...</xml>" 
} 
+1  A: 

Actually base 64 should work. But you might want to mark the property so it is clear.

{
    "Property" : {
        "Type" : "XML",
        "Encoding" : "Base64",
        "Value" : "PFhNTD48WE1MPjxYTUw+PC9YTUw+PC9YTUw+PC9YTUw+"
    }
}
ChaosPandion
Good advice, ChasPandio, thank you!
Edwin
A: 

JSON does not support binary data?

If you mean it doesn't have a bytes datatype, well who cares? JavaScript strings can contain all possible Unicode characters, including control characters:

"string1": "\u0000\u0001\u0002..."

(Not that those are even valid in XML.)

So you can, if you really must encode bytes, just map them directly to the characters of the same ordinal number:

"xml": "<el>caf\u00C3\u00A9</el>"
// "café", encoded as a UTF-8 byte sequence read as ISO-8859-1

but really for XML you'd be better off keeping it in Unicode and just JSON-encoding it like any other string:

"xml": "<el>caf\u00E9</el>"
// or assuming your channel encoding is OK, simply
"xml": "<el>café</el>"
bobince
Hi bobince, Your approach will need too much coding. Thank you anyway. As to binary support by JSON, I mean direct support (by the JSON library in whatever language) of binary data. Please Google BSON.
Edwin
You will always have to encode stuff; a standard JSON encoder should perform reasonably well. For many common cases, including your example in the question, BSON is actually *less* compact than JSON. I would not recommend it in general.
bobince
Thank you for your comments, Bobince. I'm new to JSON and I'm using Delphi with an open source library called SuperObject, I'll check if that JSON lib. will do the encoding automatically, thank you!
Edwin