Search code examples
c#jsonjson.net

Newtonsoft Json.NET JSONProperty() needs to be any random number


i can't figure out how to create a JSONProperty with any number. For example my JSON that i receive looks like this from the start:

{ "255710": { "success": true,...

The specific Problem that i have is, that the first number, in this case 255710, can be any random number. Therefore i can not deserialize it so easily.

I have tried it with:

[JsonProperty("*")] [JsonProperty()] and [JsonProperty("")] 

but i'm running out of ideas here.

Is there any smart solution for this problem? Im thankfull for every help.


Solution

  • try this

    var json ="{ \"255710\": { \"success\": true}}";
    
    var dict=JsonConvert.DeserializeObject<Dictionary<string,SuccessClass>>(json);
        
    public class SuccessClass
    {
        [JsonProperty("success")]
        public bool Success {get; set;}
    }
    

    how to use

    var success=dict["255710"].Success; // true
    

    or you can use int if you like it more

    var dict=JsonConvert.DeserializeObject<Dictionary<int,SuccessClass>>(json);
    var success=dict[255710].Success; //true
    

    or if you don't know a key name

    var key=dict.Keys.First();
        
    var success=dict[key].Success; // true
    
    // or if you don't need a key
    var successObj=dict.Values.First(); //the whole sucess class
    var success=dict.Values.First().Success; //true