I have a json that I receive in a System.IO.StreamReader. Its structure is as follows:
{
"data": [
{
"Property1": "Value1",
"Property2": "Value2"
},
{
"Property1": "Value3",
"Property2": "Value4"
}
],
"metaData": {
(some other structure)
}
}
And I have two classes, one that has Property1 as a data field, and another one that has Property2 as a data field.
I would like to use the incoming stream to deserialize this json into two separate collections of the two classes that I have.
So far, I managed to do this only by stringifying the stream first and then invoking DeserliazeObject(string) twice. But then a huge chunk of memory is allocated unnecessarily.
How can I do this by means of a single invocation to DeserializeObject(streamReader)? Does Newtonsoft expose any serialization settings that can help me with this?
This is the code that I have, which is inefficient because I convert the stream to a string before invoking the deserializer:
var responseContent = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseContent);
var records = GetRecords(jObject);
private IList<(IClass1, IClass2)> GetRecords(JObject jObject)
{
return jObject["data"]
.Children()
.Select(CreateRecord)
.ToList();
}
private (Class1, Class2) CreateRecord(JToken recordToken)
{
var object1 = recordToken.ToObject<IClass1>();
var object2 = recordToken.ToObject<IClass2>();
return (object1, object2);
}