I am working with a service that returns the following JSON. While I can use Newtonsoft to deserialize into a C# Generic, the string array of headers, then nested array of results has thrown me a curveball. Instead of mapping to a string array, I would really like to have a List that are strongly typed and mapped.
{
"rootEntity": "function",
"count": 2,
"header": [
"name",
"email",
"function"
],
"results": [
[
"12 HOURS",
"[email protected]",
"testing"
],
[
"Example",
"[email protected]",
"second"
]
]
}
The service does allow you to add more fields, which is why it includes both the headers and then results, but those results will not be strongly typed.
My goal is to have a model that looks like:
public class EventResults
{
public string? RootEntity { get; set; }
public int Count { get; set; }
public List<Events> Events { get; set; }
}
public class Events
{
public string Name { get; set; }
public string Email { get; set; }
public string Function { get; set; }
}
Is there a way to better convert this to a C# Object without hoping that same name is always in string[0]?
You have some data model like this:
And you would like to deserialize JSON to this model that has been "compressed" by converting the
Eventsarray of objects to an array of array of property values named"results", and moving the property names of each event object to a separate array of strings called"headers".You can do this with a generic converter such as the following:
Then add
[JsonProperty("results")]to theEventsproperty:Finally deserialize by adding the converter to
JsonSerializerSettings.Converterse.g. as follows:Notes:
The converter assumes that the object has a
Resultsproperty. This assumption can be changed by overridingResultsName.Serialization in the same format is not implemented. Your model will be re-serialized using default serialization as follows:
The question Deserializing JSON containing an array of headers and a separate nested array of rows deals with a similar situation where the
"results"array is to be mapped to aList<Dictionary<string, string>>.Demo fiddle here.