1

I am trying to deserialize some JSON for which the format has changed.

Previously, the JSON format was like this:

{
  "crs": [123],
  "plugins":{...},
  // other fields...
}

So, I defined my class as the following:

public class MyClass
{
    [JsonProperty("crs")]
    public List<int> { get; set; }

    // other fields
}

And I deserialized it like this:

var serializer = new JsonSerializer();
var myclass = (MyClass) serializer.Deserialize(jsonInput, typeof(MyClass));

But now, the JSON format has changed. The crs field has been removed from the root and put into plugins as in the following:

{
  "plugins": [
    {
      "crs": [
        {
          "number": 123,
          "url": "url/123"
        }
      ]
    }
  ]
}

I don't want any fields other than the number and I want to keep the original interface of MyClass, so that I don't need to modify other related methods which use it.

Which means that:

Console.writeline(myclass.crs) 
=> [123]

And I want to keep the way that I am currently deserializing.

var myclass = (MyClass) serializer.Deserialize(jsonInput, typeof(MyClass));

How do I make a modification to get this result? I was thinking I could customize the get method of crs to retrieve the number from the plugins field, but I am new to .NET so I need some help. Here is my idea:

public class MyClass
{
    public List<int> crs { get {
       // customize the get method and only retrieve the crs number from plugin field
    }}
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
rj487
  • 4,476
  • 6
  • 47
  • 88
  • Can you provide more detail about what your `json object` or `C# Model Class` looks like? `// other fields` - knowing what goes here would be more helpful. – Rezga Jul 25 '20 at 09:02

1 Answers1

1

If you define a couple of extra classes to aid in deserialization, you can use the approach you suggested.

Define a Plugin class and a Crs class like this:

public class Plugin
{
    public List<Crs> crs { get; set; }
}

public class Crs
{
    public int number { get; set; }
    public string url { get; set; }  // you can omit this field if you don't need it
}

In your MyClass class, add a plugins property as a List<Plugin>, and then you can make your crs property pull the data from the plugins list to get the List<int> you want:

public class MyClass
{
    public List<Plugin> plugins { get; set; }

    [JsonIgnore]
    public List<int> crs 
    { 
        get
        {
            return plugins.SelectMany(p => p.crs).Select(c => c.number).ToList();
        }
    }

    // other fields
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300