受欢迎的博客标签

Restful Web API returns empty json array with System.Text.Json.JsonSerializer

Published

 

I've traced through the my method (below) at run time. Below the code I've included a screenshot of the Debug examination of the Portfolios list just before the return statement. I've expanded a couple of the list entries. As you can see, each Portfolio object contains bona fide data - a numeric Id and a string name.

Yet, here's what comes back to the Chrome browser, or postman, no difference.

[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

What's happening to all the data? Thanks for your help!

public class Portfolio 
{
public int id ;
public string name ;
}
 // GET: api/Portfolio
    [HttpGet]
    public List<Portfolio> Get()
    {
        List<Portfolio> Portfolios = new List<Portfolio>();

        using (SqlConnection cn = new SqlConnection(conn))
        {
            SqlCommand cmd = cn.CreateCommand();
            cmd.CommandText = sqlSelectPortfolios;
            cn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            Portfolio pf;

            while (rdr.Read())
            {
                pf = new Portfolio
                {
                    id = (int)rdr["PortfolioId"],
                    name = (string)rdr["PortfolioName"]
                };

                Portfolios.Add(pf);
            }
        }

        return Portfolios;
    }

 

The id and name need to be public and properties. As of 3.0 System.Text.Json.JsonSerializer does not serialize fields.

Add {set;get;}

public class Portfolio 
{
public int id {get; set;}
public string name {get; set;}
}

 

2.

raw json data as follow:

{"Categories":[],"Tags":["mijia","xiaomi"],"Comments":[],"Content":

 

Add {set;}

 public IList<string> Categories { get; set; } = new List<string>();

        public IList<string> Tags { get; set; } = new List<string>();

        public IList<Comment> Comments { get; set; } = new List<Comment>();

 

.NET 9 AOT发布序列化反序列化报错System.Text.Json

MQTT 发布失败: Reflection-based serialization has been disabled for this application. Either use the source generator APIs or explicitly configure the 'JsonSerializerOptions.TypeInfoResolver' property

.创建源生成器
//加这么一句,每个要用到序列化反序列化的对象都要加

[JsonSerializable(typeof(TestModel))] 
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}

                        
原文链接:https://blog.csdn.net/wushuaihua520/article/details/143952057