3

Hi guys I have a JSON like the one below

{
  "totals": {
    "tokenType": "string",
    "tokenDenomination": "double",
    "count": "int"
  },
  "IDCode": "string",
  "Key": "string"
}

and c# code to deserialize in to object is

internal class GetTokenRootInfo
{
    public  static Totals totals{ get; set;}
    public  static string IDCode{ get; set;}
    public  static string Key{ get; set;}
}

When I use jsonconvert.DeserializeObject<gettokenrootinfo>(json); nothing is being set and every var is a null.

But if I remove static types then everything works.

Can any one tell me the reason why static types are not working when deserializing the object?

3
  • 6
    Because they're static? Seriously, I'm guessing that there might be some misuse of static members going on because it doesn't make a lot of sense to deserialize data into static members. Commented Mar 24, 2014 at 9:35
  • 9
    @KeithPayne One exception is when you use a static config class. It's useful to have config static for ease of access. A static constructor can load properties from disk and set them. (De)serializing the config class means you can simply us Config.MaxConnections, Config.Save(), Config.Load(), etc... Commented May 10, 2015 at 3:36
  • @Keith: it is extremely useful; you have many cases where an app may need access to global settings for its operation; And building some cosmetic scaffolding to access data is not necessarily a priority. Commented Nov 18, 2018 at 14:00

1 Answer 1

7

If you really want to deserialize to static members on the class, you can explicitly mark them with a [JsonProperty] attribute, and that will allow it to work:

internal class GetTokenRootInfo
{
    [JsonProperty("totals")]
    public static Totals totals { get; set; }
    [JsonProperty("IDCode")]
    public static string IDCode { get; set; }
    [JsonProperty("Key")]
    public static string Key { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @brain yes i have already done it after a bit of research.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.