简体   繁体   English

API Json 响应 C# 对象的首字母大写属性

[英]API Json response to C# Object with capital case properties first letter

I've made an API where after an Entity Framework elaboration I send an object serialized in Json.我制作了一个 API,在实体框架详述之后,我发送了一个在 Json 中序列化的对象。

My Object:我的对象:

public class Package
{
    public int Items { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public double? Weight { get; set; }
    public string Size { get; set; }
    public string PackageType { get; set; }
}

The problem start when after recieve it (Xamarin app) the Json have the first letter lowercase, but I want deserialize it in the exact same class and it can't because the class have properties in capitalcase (C# standard).当收到它(Xamarin 应用程序)后,问题就开始了,Json 的第一个字母小写,但我想在完全相同的类中反序列化它,但不能,因为该类具有大写的属性(C# 标准)。 Now I'm using a horrible 'helper' class that have the properties in lowercase for translating it.现在我正在使用一个可怕的“助手”类,它具有小写的属性来翻译它。

Any idea how to handle this and send the Json directly with capital case first letter?知道如何处理这个问题并直接用大写首字母发送 Json 吗?

Edit编辑

I use ASP.NET web API Core and Newtonsoft.Json我使用ASP.NET Web API CoreNewtonsoft.Json

In Xamarin app I use System.Text.Json在 Xamarin 应用程序中,我使用System.Text.Json

You have to change the default property naming policy on the json serialization options.您必须更改 json 序列化选项的默认属性命名策略。

By default it's set to camel case but if you set it to null , the property names are to remain unchanged (or remain as you wrote on your class).默认情况下,它设置为驼峰式大小写,但如果您将其设置为null ,则属性名称将保持不变(或保持您在课堂上所写的内容)。

Simply add this to your Startup.cs :只需将此添加到您的Startup.cs

services.AddControllers()
.AddJsonOptions(options =>
{
   options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

By default, ASP.NET Core encodes all JSON properties names in camel case, to match JSON conventions (see the announcement of the change on GitHub ).默认情况下,ASP.NET Core 将所有 JSON 属性名称编码为驼峰格式,以匹配 JSON 约定(请参阅GitHub 上的更改公告)。

If you want to keep the C# conventions, you need to change the default JSON serializer.如果要保留 C# 约定,则需要更改默认的 JSON 序列化程序。

In your Startup.cs , configure the MVC part like this (ASP.Net Core 3.0):在您的Startup.cs ,像这样配置 MVC 部分(ASP.Net Core 3.0):

services
    .AddMvc()
    .AddNewtonsoftJson(options =>
    {
        // don't serialize with CamelCase (see https://github.com/aspnet/Announcements/issues/194)
        jsonSettings.ContractResolver = new JsonContractResolver();
    });

For ASP.NET Core 2.0 :对于 ASP.NET Core 2.0 :

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        // don't serialize with CamelCase (see https://github.com/aspnet/Announcements/issues/194)
        jsonSettings.ContractResolver = new DefaultContractResolver();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM