Reputation: 13
I am aware of several open source java libraries that will convert XML to JSON.
However, I am looking for a library (or way) that will suppress the leading @ that is prepended to the element attribute. So, for example, given the JSON string below:
{ "description":
{ "@lang":"en-us",
"@maxlength":"500",
"#text":"Vitamin D Supplementation"
}
}
I would like to produce the following JSON string (notice the missing @ in front of "lang" and "maxlength"):
{ "description":
{ "lang":"en-us",
"maxlength":"500",
"#text":"Vitamin D Supplementation"
}
}
As far as I can tell, no libraries offer a way to do this. Maybe there is a way to accomplish this using Regex, though I would have to be careful of not stripping valid @ characters in data?
Upvotes: 1
Views: 1666
Reputation: 2146
String.replace("\"@", "\"")
or what?
UPDATE
To prevent replacing the @ within a string value, you could use the regexp version of replace. You'd look for the @ sign preceded by " and not preceded by some X, where X is a colon (:) followed by any number of whitespace. You'd replace by the " again.
A less hacky approach would be to have a library stream the json in a content-event-like fashion, catch any object member name events, replace such member names that begin with an @ accordingly and then throw them back to the event stream. That stream would then be converted to JSON text again. (I'm currently working on a library that provides such functionality, but it's not yet published, unfortunately.)
Similarly, you could hook in the XML to JSON translation process. The translator would have to stream the XML to some sort of XML content events, which are later converted to JSON content events, which are then stringified to JSON text. (Ok, that's how I would do it.) If you could plug in at either side of the JSON events stage, you could easily translate specific object member names. Obviously the library you use would have to make plugging in possible, if only by offering the steps of the process for separate invocation.
(In case you wondered, "object member name" is the part before the : in a JSON object, the "value" is the part after it.)
Upvotes: 1