How to convert Json data directly into xml - standardized way? I'm having a Json:

[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]


And I want it to convert into XML:

&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;Us&gt;
    &lt;U1&gt;
        &lt;S&gt;a&lt;/S&gt;
        &lt;D&gt;b&lt;/D&gt;
    &lt;/U1&gt;
    &lt;U1&gt;
        &lt;S&gt;s1&lt;/S&gt;
        &lt;D&gt;m1&lt;/D&gt;
    &lt;/U1&gt;
&lt;/Us&gt;


I know the php way, first decoding json using Json_decode() and a bunch of foreach loop that finally generate XML.

But I want in Drupal way. There is a module serialization in core of Drupal 8. But don't know how can I take the services from that module in my custom one.

Also, I got a link, How to get it done using symfony, but again it seems like Drupal 8 standards are lacking somewhere by me.

What's the right approach to achieve this in Drupal way.
The Serializer component is a tool in your Drupal toolbox that should be used when you need to serialize and deserialize data from and to Drupal data such as entities. Unfortunately you cannot deserialize into a \StdClass without implementing your own normalizer.

Inject the serializer service into your class, and use the serialize method to normalize the non-Drupal decoded JSON array into XML.

// Inject this instead of using \Drupal
$serializer = \Drupal::get('serializer');
// Use json_decode or @4k4's example above and use associative arrays instead of object.
$json = json_decode('[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]', TRUE);
// Unfortunately it seems that for an array serializer xml_root_node_name won't work so wrap $json in the root name.
$data = ['US' =&gt; $json];
// Serialize into XML.
$xml = $serializer-&gt;serialize(
  $data,
  'xml',
  ['xml_root_node_name' =&gt; 'US']);