1

I got a bunch of conversions to make where I am converting a JSON data structure from a superset to a subset. EX:

A : 
{
  Name {
    first: bob
    middle: john
    last : bobster    
  }
}

B : 
{
  Name {
    first: bob
    last : bobster    
  }
}

Both have a json schema describing their structure, and structure is exactly the same, is that B is simply missing some properties from A

Any ideas for an easy way to map A to B (essentially stripping A of properties that do not exist in B)? I am wondering if there is some library or C# language capabilities that could make this trivial.

Using C# and .NET Core.

Greg Bala
  • 3,563
  • 7
  • 33
  • 43

2 Answers2

5

Create an object for the subset like:

public class Name{
public string first{get;set;}
public string last {get;set;}
}

Deserialize the json to the subset object:

var test = JsonConvert.DeserializeObject<Name>(superset);

Then you can use this to convert back to json if needed:

JsonConvert.SerializeObject(subset)
Joy
  • 64
  • 4
1

You can use inheritance to cast objects from a subclass to another class.

Given the following json

{
    "Name": 
    {
        "first": "bob",
        "middle": "john",
        "last" : "bobster"
    }
}

You can create some C# classes that match the json structure as follows:

public class Model
{
    public FullName Name { get; set; }
}

public class Name
{
    [JsonProperty("first")]
    public string First { get; set; }

    [JsonProperty("last")]
    public string Last { get; set; }
}


public class FullName : Name
{
    [JsonProperty("middle")]
    public string Middle { get; set; }
}

Please note that:

  • FullName inherits from Name
  • class Model has a property of type FullName (i.e. the most specific object)

You can deserialize an object of type Model and then cast the Name property as follows:

string json = @"{
    ""Name"": 
    {
        ""first"": ""bob"",
        ""middle"": ""john"",
        ""last"" : ""bobster""
    }
}";

Model model = JsonConvert.DeserializeObject<Model>(json);
Name name = model.Name as Name;

Edit

As an alternative, you can create a generic class as follows

public class Model<TName> where TName : Name
{
    public TName Name { get; set; }
}

Deserializing the json:

string json = @"{
    ""Name"": 
    {
        ""first"": ""bob"",
        ""middle"": ""john"",
        ""last"" : ""bobster""
    }
}";

var fullName = JsonConvert.DeserializeObject<Model<FullName>>(json);
var name = JsonConvert.DeserializeObject<Model<Name>>(json);
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86