嗨,我想弄清楚对象一旦序列化后如何在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; } }
}
这样可以解决您的问题。
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