简体   繁体   中英

Convert Xml response of Api call to json

I am calling an external API which returns me XML response but I want to convert it to json so that the frontend can use it.

I tried to set the request header to application/json but seems like the API returns only XML.

Similar kind of question is answered here - convert-xml-to-json
Try

import org.json.XML;

and then use

JSONObject jsonObject = XML.toJSONObject("<XMLStringValue>");

I've open sourced a library called unXml , that lets you create a parser that consumes xml, and produces Jackson json ObjectNodes or ArrayNodes .

It's available here on Maven Central .

Example:

Input xml:

<root>
  <id>1</id>
  <title>mytitle</title>
</root>

Creating the parser in Java:

import com.nerdforge.unxml.Parsing;
import com.nerdforge.unxml.factory.ParsingFactory;
...

public class MyController {
    public ObjectNode getJsonFromXml(String inputXmlString) {
        Parsing parsing = ParsingFactory.getInstance().create();
        Document document = parsing.xml().document(inputXmlString);

        Parser<ObjectNode> parser = parsing.obj("root")
            .attribute("id", "id", parsing.number())
            .attribute("title")
            .build();

        ObjectNode node = parser.apply(document);
        return node;
    }
}

Gives the following json-result:

{
  "id":1,
  "title":"mytitle"
}

Try this IT worked for me,

  header('Content-Type: application/xml');

  $response=simplexml_load_string($response);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM