Search code examples
c#jsonunity-game-enginemonodeserialization

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


I'm obtaining that response from server:

{
    "auth_token": "062450b9dd7e189f43427fbc5386f7771ba59467"
}

And for accessing it I need to use same name as in original 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);
    }
}

How to rename TokenResponse.auth_token to TokenResponse.authToken without losing the functionality?


Solution

  • I suppose this is a code for Unity. Unfortunately it does not seem to allow you to change the key name of JSON string out of box.

    However the documentation says you can use [NonSerialized] attribute to omit fields. So the following code might let you do what you want.

    [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);
        }
    }
    

    Hope this helps.