I’m having a well-defined class for sending as JSON body in an HTTP request.
public class EventData
{
public string deviceJobId { get; set; }
public int eventID { get; set; }
public long time_ms { get; set; }
/// similar fields
}
Now I have to add one more field called HealthInfo
. The value of this new HealthInfo
is a nested JSON read from some file.
The fields of this JSON file change from time to time, and there is no guarantee that some fields will always be present.
I don’t want to read/modify any value of that and just need to publish this EventData
as a json as part of an HTTP request.
Then how to add HealthInfo
correctly?
I tried to put HealthInfo
as string and object is getting double serialized.
3
Answers
If you know all of the possible properties inside HealthInfo then you can create new class
HealthInfo
with nullable properties.and then add nullable HealthInfo in your main class:
However if you’re not sure what kind of data you’re gonna get and want to avoid double serialization, just pass HealthInfo as object:
you have to convert to JObject before you add new json string
You can use of C# reflection. (TypeBuilder.DefineProperty Method)
In fact you must add prop to the class in run time.
see full information at
https://learn.microsoft.com/