gpt4 book ai didi

c# - 如何基于属性使用 JSON.NET 序列化枚举?

转载 作者:太空狗 更新时间:2023-10-29 23:20:39 24 4
gpt4 key购买 nike

下面的代码生成输出为 {"error_message":null,"status":"InvalidRequest"} 我想将其作为 {"error_message":null,"status ":"INVALID_REQUEST"}

很简单,我想知道如何在使用 JSON.NET 序列化时遵守 PropertyName 属性?

void Main()
{
var payload = new GooglePlacesPayload();
payload.Status = StatusCode.InvalidRequest;
JsonConvert.SerializeObject(payload).Dump();
}

public class GooglePlacesPayload
{
[JsonProperty(PropertyName = "error_message")]
public string ErrorMessage { get; set; }

[JsonProperty(PropertyName = "status")]
[JsonConverter(typeof(StringEnumConverter))]
public StatusCode Status { get; set; }
}

[Flags]
public enum StatusCode
{
// reference https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits#limitexceeded
// reference https://developers.google.com/places/web-service/search#PlaceSearchStatusCodes

None = 0,

// indicates that no errors occurred; the place was successfully detected and at least one result was returned.
[JsonProperty(PropertyName = "OK")]
Ok = 1,
// indicates that the search was successful but returned no results. This may occur if the search was passed a latlng in a remote location.
[JsonProperty(PropertyName = "ZERO_RESULTS")]
ZeroResults = 2,
// indicates that you are over your quota. The daily quotas are reset at midnight, Pacific Time.
[JsonProperty(PropertyName = "OVER_QUERY_LIMIT")]
OverQueryLimit = 4,
// indicates that your request was denied, generally because of lack of an invalid key parameter.
[JsonProperty(PropertyName = "REQUEST_DENIED")]
RequestDenied = 8,
// generally indicates that a required query parameter (location or radius) is missing.
[JsonProperty(PropertyName = "INVALID_REQUEST")]
InvalidRequest = 16,

// When the Google Places service returns a status code other than OK, there may be an additional error_message field within the search response object.
// This field contains more detailed information about the reasons behind the given status code.
Positive = Ok | ZeroResults,
Negative = OverQueryLimit | RequestDenied | InvalidRequest

}

最佳答案

[EnumMember(Value="INVALID_REQUEST")] 应该这样做。请注意,这是一个 dotnet 核心属性,不是特定于 newtonsoft 的,因此它可能也会影响其他事物。

关于c# - 如何基于属性使用 JSON.NET 序列化枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com