Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
While you can create JSON using the tWriteJSONField component, if you want to simply convert an XML String into JSON (with the same format), there is a much simpler way.
All you need to do is use the json-org.jar (which can be downloaded here) and a Talend routine. I have included an example of a routine below.....
package routines; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; public class XmlToJSON { public static String xmlToJson(String xml){ String json =""; try { JSONObject xmlJSONObj = XML.toJSONObject(xml); json = xmlJSONObj.toString(); } catch (JSONException je) { System.out.println(je.toString()); } return json; } }
Once you have created the routine, right click on the routine in the project tree and select "Edit Routine Libraries". Then point it towards the Jar downloaded above.
Then all you need to do is create your XML, convert it to a String (use a tConvertType), then use your routine method to convert the XML String to a JSON String.
Easy
Hi Sixteen Stars,
Thank you for tuto. I've been surching a little time for a code like this. First i've found user components named : tConvertXMLtoJSON or the tXMLtoJson. They do the same as your routine. There is only one common think with the components and your routine, the take the xml tree in an intil order but the don't reproduce the same order. Element order is not respected. I don't know why because there is no attributs to specify any order. It's a real problem for me because the transformed JSON has an order to respect because of the API REST need on order (the order i've created in the enter XML) . Do you have an idea about this, please ?
Thank you
Marc.
Take a look here: https://github.com/stleary/JSON-java/issues/383
....and here: https://github.com/stleary/JSON-java/wiki/FAQ#why-isnt-ordering-allowed-in-jsonobjects
I'm sure this can be achieved, but it shouldn't be needed. There is a recommendation in the first link
If the API needs the elements to be in a specific order, then it isn't JSON. It's a custom format that looks a lot like like JSON but has ordering semantics added. You can't expect a generic JSON component to support the requirements of a non-standard data format.