I have two JSON files: One for Locations, another for Objects at a location.
locations.json =>
[
{
"Name": "Location#1",
"X": 0,
"Y": 20
},
{
"Name": "Location#2",
"X": 0,
"Y": 19
},
...
]
objects.json ==>
[
{
"Name": "Piano",
"CurrentLocation": "Location#1"
},
{
"Name": "Violin",
"CurrentLocation": "Location#2"
},
...
]
The objects.json references the locations instances using the location names.
I have two classes that this deserializes to (or serializes from):
public class ObjectOfInterest
{
[JsonPropertyName("Name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("CurrentLocation")]
public LocationNode CurrentLocation { get; set; } = new()
}
public class Location
{
[JsonPropertyName("Name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("X")]
public float X { get; set; }
[JsonPropertyName("Y")]
public float Y { get; set; }
}
How do I create a custom JSONSerializer or Converter that takes the string Location name JSON attribute, and assigns the correct location instance to the Objects class?
2
Answers
It turns out that the JSON Converter was overkill. I ended up indexing the locations by their Name. And then making an additional public string type that mapped to the indexed private Location type (renamed to _currentLocation since we can't have two properties with the same name) I needed.
Add a JsonConverterAttribute to the CurrentLocation property
The converter should store the locations indexed by their name:
Finaly, you can use the LocationConverter like that: