如何为 System.Serializable class 设置自定义 json 字段名称?

How to set custom json field name for System.Serializable class?

我正在从服务器获取该响应:

{
    "auth_token": "062450b9dd7e189f43427fbc5386f7771ba59467"
}

为了访问它,我需要使用与原始 JSON 相同的名称。

[System.Serializable]
public class TokenResponse
{
    public string auth_token; // I want to rename it to authToken without renaming corresponding field in json
    public static TokenResponse CreateFromJSON(string json) {
        return JsonUtility.FromJson<TokenResponse>(json);
    }
}

如何在不丢失功能的情况下将 TokenResponse.auth_token 重命名为 TokenResponse.authToken?

我想这是 Unity 的代码。不幸的是,它似乎不允许您开箱即用地更改 JSON 字符串的键名。

但是 the documentation 表示您可以使用 [NonSerialized] 属性来省略字段。所以下面的代码可能会让你做你想做的事。

[System.Serializable]
public class TokenResponse
{
    [NonSerialized]
    public string AuthToken;

    public string auth_token { get { return AuthToken; } }

    public static TokenResponse CreateFromJSON(string json)
    {
        return JsonUtility.FromJson<TokenResponse>(json);
    }
}

希望对您有所帮助。

is close to a good solution for Unity, but unfortunately doesn't quite work (because Unity never serializes C# properties).

这是他的答案的一个变体,可以在 Unity 中正确编译和工作(在 Unity 2018.3.1 中测试)

[System.Serializable]
public class TokenResponse
{
    [SerializeField] private string auth_token;
    public string authToken { get { return auth_token; } }

    public static TokenResponse CreateFromJSON(string json) {
        return JsonUtility.FromJson<TokenResponse>(json);
    }
}

使用JsonDotNet代替JsonUtility

只需这样做:

[System.Serializable]
public class TokenResponse
{
    // what is `JsonProperty` see:https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm
    [JsonProperty("auth_token")] 
    public string authToken {set; get;} 

    public static TokenResponse CreateFromJSON(string json) {
        return JsonConvert.DeserializeObject<TokenResponse>(json);
    }
}