2

I have JSON which looks like the following:

[
    {
        "id": 7,
        "name": "Example 1",
        "player_class": 2,
        "player_class_name": "Class1",
        "url": "/someurl",
        "standard_ccp_signature_core": {
          "as_of": "2019-07-04T16:46:23.760Z",
          "format": 2,
          "components": [ 742, 51779, 51790, 503, 52810, 52819, 381, 49164, 48886, 56223 ]
        },
        "wild_ccp_signature_core": null
    }
]

The generated class looks like the following:

public class Archetype 
{
    public int id { get; set; }
    public string name { get; set; }
    public string player_class_name { get; set; }

    [JsonProperty("standard_ccp_signature_core")]
    public StandardCcpSignatureCore core_cards { get; set; }
}

public class StandardCcpSignatureCore 
{
    public List<int> components { get; set; }
}

I would like to simplify the Archetype class a little so that it looks like this:

public class Archetype 
{
    public int id { get; set; }
    public string name { get; set; }
    public int player_class { get; set; }
    public string player_class_name { get; set; }

    [JsonProperty("standard_ccp_signature_core")]
    public List<int> components { get; set; }  
}

Is this possible using the Newtonsoft deserializer? I am pretty sure I have to setup a JsonObject attribute on the components property of my Archetype class, but am unsure of how to tell it how to do this.

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
  • Could you just add in an additonal property? "public List components { get { return core_cards.components; } set { core_cards.components = value; } }". Obviously not a great solution if it's a very large object you're trying to avoid keeping/parsing. – Andy Nugent Jul 23 '19 at 14:07

1 Answers1

0

You can do it with the following converter:

public class ArchetypeConverter : JsonConverter
{ 
    public override bool CanConvert(Type objectType)
    {
        return typeof(Archetype).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = JObject.Load(reader);
        var token = obj.SelectToken("standard_ccp_signature_core.components");

        if (token != null)
            obj.Add(token.Parent);

        using (reader = obj.CreateReader())
        {
            existingValue = (existingValue ?? new Archetype());
            serializer.Populate(reader, existingValue);
        }
        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Model:

[JsonConverter(typeof(ArchetypeConverter))]
public class Archetype
{
    public int id { get; set; }
    public string name { get; set; }
    public int player_class { get; set; }
    public string player_class_name { get; set; }
    public List<int> components { get; set; }
}