Warm tip: This article is reproduced from stackoverflow.com, please click
api c# json post

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

发布于 2020-04-11 22:18:32

Hi I would like to figure out how once an object is serialized how to map the fields in the POST API model?

I cannot seem to figure it out , please see code below, I have solved the serialization and can show the results from my SQL query in the console, but how do you map them to the fields that should be populated in the 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 =;

ProductSQL.cs

public class ProductSQL { 
    public string sku { get; set; } 
    public string title { get; set; } 
    public string description { get; set; } } 
}
Questioner
Bradley
Viewed
86
Mr.AF 2020-02-02 18:41

This solves your problem.

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;
}

You do not need to use serialized object for mapping just use your myObjectList