温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - C# Serialized JSON object cannot map to destination fields for POST
api c# json post

其他 - C#序列化JSON对象无法映射到POST的目标字段

发布于 2020-04-12 09:39:23

嗨,我想弄清楚对象一旦序列化后如何在POST API模型中映射字段?

我似乎无法弄清楚,请参见下面的代码,我已经解决了序列化问题,并且可以在控制台中显示SQL查询的结果,但是如何将它们映射到应该在API中填充的字段?

using (SqlCommand command = new SqlCommand(query, connection))
{
    connection.Open();
    List<ProductSQL> myObjectList = new List<ProductSQL>();
    var reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            ProductSQL myObject = new ProductSQL();
            myObject.sku = reader["sku"].ToString();  
            myObject.description = reader["description"].ToString();
            myObjectList.Add(myObject);
        }
    }
    var JsonResult = JsonConvert.SerializeObject(myObjectList);
    Console.WriteLine(JsonResult);
}


/* Program Initialization Now need to map the products to their respective fields from the SQL Database to the API*/

Console.WriteLine("Post Articles To API");
HttpResponseMessage response2;
Product NewProduct = new Product();
NewProduct.sku = <What to do here , I would like to map this to the serialized JSON> ;
NewProduct.title = ;
NewProduct.description =;

产品SQL.cs

public class ProductSQL { 
    public string sku { get; set; } 
    public string title { get; set; } 
    public string description { get; set; } } 
}

查看更多

提问者
Bradley
被浏览
107
Mr.AF 2020-02-02 18:41

这样可以解决您的问题。

List<ProductSQL> myObjectList = new List<ProductSQL>();
using (SqlCommand command = new SqlCommand(query, connection))
{
    connection.Open();
    var reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            ProductSQL myObject = new ProductSQL();
            myObject.sku = reader["sku"].ToString();  
            myObject.description = reader["description"].ToString();
            myObjectList.Add(myObject);
        }
    }
    var JsonResult = JsonConvert.SerializeObject(myObjectList);
    Console.WriteLine(JsonResult);
}


/* Program Initialization Now need to map the products to their respective fields from the SQL Database to the API*/

Console.WriteLine("Post Articles To API");
HttpResponseMessage response2;
foreach(ProductSQL product in myObjectList.ToList())
{
    Product NewProduct = new Product();
    NewProduct.sku = product.sku;
    NewProduct.title = product.title;
    NewProduct.description =product.description;
}

您不需要使用序列化的对象进行映射,只需使用 myObjectList