Search code examples
c#jsonoopjson-deserializationsoftware-design

Json deserialization with multiple json file for Multiplicity relationship


I have an object model as below, some of the objects have zero or more relationships

public class Foo
{
 public string Id
 public string Name
}

public class Bar
{
 public string Id
 public Foo Foo
 public DateTime At
}

public class Baz
{
 public string Id
 public DateTime At
 public List<Bar> Bars
}

public class Qux
{
 public string Id
 public string Name
 public List<Baz> Baz
}

I need to deserialize the following 4 json files.

Foo.json

[
  {
    "Id": "1",
    "Name": "AAA"
  },
  {
    "Id": "2",
    "Name": "BBB"
  }
]

Bar.json

[
  {
    "Id": "1",
    "FooId": "1",
    "BazId": "1",
    "At": "2022-01-01T10:00:00"
  },
  {
    "Id": "2",
    "FooId": "2",
    "BazId": "1",
    "At": "2022-01-02T10:00:00"
  }
]

Baz.json

[
  {
    "Id": "1",
    "Quxd": "1",
    "At": "2022-01-01T10:00:00"
  },
  {
    "Id": "2",
    "QuxId": "1",
    "At": "2022-01-02T10:00:00"
  }
]

Qux.Json

[
  {
    "Id": "1",
    "Name": "CCC"
  },
  {
    "Id": "2",
    "Name": "DDD"
  }
]

I know it is a badly designed JSON file and I cannot change that and that is my challenge to resolve it without changing the json.

I was able to solve the issue, by creating another 4 sets of objects for each JSON and deserializing them individually, after that, I will have a loop for object4 to map all other objects.

But I feel it is not that efficient.

Please let me know if you have any other ideas so that I can solve this in a much better way.

Thanks


Solution

  • This is badly formatted json, so please ignore