2016-11-29 93 views
4

代碼生成作爲{"error_message":null,"status":"InvalidRequest"}輸出,其中我想獲得它作爲{"error_message":null,"status":"INVALID_REQUEST"}如何基於屬性序列化與JSON.NET的枚舉?下面

所以簡單地說,我不知道如何兌現PropertyName屬性,同時與JSON.NET序列化?

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 

} 
+0

我假定你正在尋找*任何*的方式來改變枚舉的序列化。如果你正在尋找一種使用'PropertyName'的方法,隨時恢復並添加一個更新到你的問題。 –

+0

你的假設是正確的。謝謝! – cilerler

回答

3

[EnumMember(Value="INVALID_REQUEST")]應該這樣做。請注意,這是一個dotnet核心屬性,不是特定於newtonsoft的,所以它也可能影響其他內容。

+0

幸運的是我在[tag:dotnet-core]看起來好像你只要添加'System.Runtime.Serialization'它就可以在兩個世界上順利工作。謝謝! – cilerler

+1

@cilerler呵呵,我的意思是「dotnet的核心屬性」,而不是「dotnet-core的屬性」。命名的東西.... –