【问题标题】:How to convert JSON response to XML in C#?如何在 C# 中将 JSON 响应转换为 XML?
【发布时间】:2020-02-28 07:25:32
【问题描述】:

我有一个 JSON 格式的 API 响应,如何在 c# 中将其转换为 XML 响应

我不知道将 JSON 转换为 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;
        }

我希望将该响应更改为 XML

【问题讨论】:

标签: c# asp.net json xml


【解决方案1】:

转到Global.asax,但在Application_Start() 中遵循代码:

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

或转到WebApiConfig.cs 并将此行放入Register(HttpConfiguration config)

config.Formatters.XmlFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));  

【讨论】:

  • 注:这不会将 JSON 转换为 XML,它会生成 XML 而不是 JSON。从来没有任何 JSON,这是实现 OP 真正想要的正确方法,而不是他们所说的字面意思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 2015-10-04
  • 2020-10-22
相关资源
最近更新 更多