0

I have an API response in JSON format, how can I convert it to XML response in c#

i don't know the placement of the script to convert JSON to XML

public static async Task<List<PointMaster>> ExecuteTest(string query)
        {
            string connStrResult = ConfigurationManager.ConnectionStrings["PostGresConnection"].ConnectionString;
            NpgsqlConnection connection;
            NpgsqlCommand command;
            NpgsqlDataReader reader;

            List<PointMaster> master = new List<PointMaster>();
            connection = new NpgsqlConnection(connStrResult);
            connection.Open();
            command = new NpgsqlCommand(query, connection);
            reader = command.ExecuteReader();

            while (await reader.ReadAsync())
            {
                PointMaster point = new PointMaster
                {
                    point_id        = Convert.ToString(reader["point_id"]),
                    point_type      = (string)reader["point_type"],
                    sp_geometry     = (PostgisPoint)(reader["sp_geometry"]),
                    msid            = Convert.ToInt32(reader["msid"]),

                };

                master.Add(point);
            }

            return master;
        }

I want that response to be changed to XML

codeherk
  • 1,609
  • 15
  • 24
Figi
  • 1
  • Have a look at this question https://stackoverflow.com/questions/18266952/asp-net-web-api-returning-xml-instead-of-json and the question that it links to as well. I think you will find what you are looking for. – Shane Haw Nov 02 '19 at 06:26
  • Does this answer your question? [ASP.NET web api returning XML instead of JSON](https://stackoverflow.com/questions/18266952/asp-net-web-api-returning-xml-instead-of-json) – Shane Haw Nov 02 '19 at 06:27

1 Answers1

0

Go to Global.asax and but following code in Application_Start() :

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseDataContractSerializer = true;

Or go to WebApiConfig.cs and put this line in Register(HttpConfiguration config) :

config.Formatters.XmlFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));  
Muhammad Aftab
  • 1,098
  • 8
  • 19
  • N.b. this doesn't turn JSON *into* XML, it generates XML *instead of* JSON. There is never any JSON, This is the right way to achieve what the OP actually wants, just not literally what they said. – Tom W Nov 02 '19 at 08:40