.net 序列化数据时忽略JsonPropertyName

f45qwnt8  于 2023-06-07  发布在  .NET
关注(0)|答案(1)|浏览(153)

我试图添加一个属性序列化名称,但我尝试过的解决方案似乎都不起作用,当JSON发送short_name时,我总是得到null值,(如果请求更改为shortName,则所有工作正常)。
我尝试同时使用[JsonPropertyName("short_name")][JsonProperty("short_name")]
但都没有用。
下面是完整的类:

public class ProductPayload
{
    public string Id { get; set; }
    [JsonProperty(PropertyName = "short_name")]
    public string ShortName { get; set; }
    public string Name { get; set; }
    public string UnitOfMeasure { get; set; }
    public int Vat { get; set; }
    public decimal Price { get; set; }
    public decimal PurchasePrice { get; set; }
    public Category Category { get; set; }
    public Group Group { get; set; }
    public Department Department { get; set; }
    public Family Family { get; set; }
    public Dictionary<string, List<int>> ActivePrinters { get; set; }
    public List<Pricing> Pricing { get; set; }
    public string Background { get; set; }
    public string Color { get; set; }
}

然后从控制器中期望如下所示:

[HttpPost("products")]
public async Task<IActionResult> ReceiveProducts([FromBody] List<ProductPayload> payload)
{
    await _payloadRepository.InsertProducts(payload);
    return Ok();
}

该项目在.NET 6中

The JSON:

[
    {
        "id": "ABC123",
        "short_name": "Descrizione tasto",
        "name": "Descrizione estesa",
        "unitOfMeasure": "PZ",
        "vat": 10,
        "price": 12.9,
        "purchasePrice": 4.85,
        "category": {
            "id": "5fc98b530536fc0011d7f9a2",
            "name": "TEST"
        },
        "group": {
            "id": "001",
            "name": "Reparto cassa"
        },
        "department": {
            "id": "001",
            "name": "Reparto"
        },
        "family": {
            "id": "001",
            "name": "Famiglia"
        },
        "activePrinters": {
            "1": [
                1,
                3
            ],
            "2": []
        },
        "pricing": [
            {
                "id": 2,
                "price": 11.9
            },
            {
                "id": 5,
                "price": 10.8
            }
        ],
        "background": "#000000",
        "color": "#ffffff"
    }
]

Startup.cs:
public class Startup { public Startup(IConfiguration configuration){ Configuration = configuration;}

public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        RegisterScopedServices(services);

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
                    .SetIsOriginAllowed(hostName => true);
                });
        });

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = "https://example.com",
                ValidAudience = "https://example.com",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("TEST")),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true
            };
        });

        services.Configure<IISServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo { 
                Title = "API",
                Version = "v1",
                Description = "API Documentation."
            });

            var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
        });

        services.AddControllersWithViews();
    }

    private void RegisterScopedServices(IServiceCollection services)
    {
        services.AddHttpContextAccessor();
        services.AddScoped<DB>();
        services.AddScoped<IAuthRepository, AuthRepository>();
        ...
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseSwaggerAuthorized();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("v1/swagger.json", "API v1");
        });

        app.UseCors();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
z2acfund

z2acfund1#

我在这里有点冒险,但我怀疑你的项目的控制器/后端正在使用System.Text.Json序列化器,它不理解Newtonsoft.Json属性注解,比如[JsonProperty]
尝试使用等效的System.Text.Json属性[JsonPropertyName]

[JsonPropertyName("short_name")]
    public string ShortName { get; set; }

看看这是否能改善你的处境。

相关问题