嗨,我想弄清楚对象一旦序列化后如何在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 =;
您还必须反序列化Resopnse流,就像您为序列化对象所做的一样。
考虑响应json流如下所示,因此我们正在尝试将其映射到对象
{
"key_1":"value_1",
"key_2":"value_2"
}
我确实使用此键的属性名称创建一个类
pubic class ResponseMode
{
public string key_1 {get;set;}
public string key_2 {get;set;}
}
请记住,键名称必须等于字段名称,否则字段将为空。最终:
JsonConvert.DerializeObject<ResponseMode>(ResponseStream);