سؤال

I am using these classes:

public class MasteryPages
{
    internal MasteryPages() { }

    [JsonProperty("pages")]
    public List<MasteryPage> Pages { get; set; }

    [JsonProperty("summonerId")]
    public long SummonerId { get; set; }
}

[Serializable]
public class MasteryPage
{
    internal MasteryPage() { }

    [JsonProperty("current")]
    public bool Current { get; set; }

    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("talents")]
    public List<Talent> Talents { get; set; }
}

[Serializable]
public class Talent
{
    internal Talent() { }

    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("rank")]
    public int Rank { get; set; }
}

This is the code I'm using to deserialise the object

//MASTERIES
var jsonMasteries = requester.CreateRequest(string.Format(RootUrl, Region) + string.Format(MasteriesUrl, summonerId));                       
var objAllMasteryPages = JsonConvert.DeserializeObject<MasteryPages>(jsonMasteries);

The jsonMasteries object is correctly serialized and gives me this: http://pastebin.com/3dkdDHdx (Rather large, to view easily: go to http://www.jsoneditoronline.org/ and paste it)

The second line is giving me troubles however. Normally my object should be filled with the data. It unfortunately isn't and I have no idea what's wrong.

Anyone could help me out?

هل كانت مفيدة؟

المحلول

Your problem is in this part of serialized JSON: "42177333": { ... }

As I understand - this is some kind of ID and it's dynamic. Possible solutions are:

  • One of possible resolutions is here: C# deserialize dynamic JSON
  • Cut this part of dynamic JSON.
  • Try to modify the serialization stuff to avoid this dynamic ID.

نصائح أخرى

Thanks to sleepwalker I saw what was wrong. (Dynamic Id (number), first line)

Now, the James Newtonking JSON library has a solution for dynamic id's like this. I edited my code to this:

var jsonMasteries = requester.CreateRequest(string.Format(RootUrl, Region) + string.Format(MasteriesUrl, summonerId));
var  objAllMasteriePages = JsonConvert.DeserializeObject<Dictionary<long, MasteryPages>>(jsonMasteries).Values.FirstOrDefault().Pages;

(First line stays the same, the magic is in the second line) Now, i use a dictionary with the key being my given Id, and my custom class.

This works wonders

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top