簡體   English   中英

C# 序列化 JSON 對象無法映射到 POST 的目標字段

[英]C# Serialized JSON object cannot map to destination fields for POST

嗨,我想弄清楚一旦對象被序列化如何映射 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM