Home > OS >  how to put anonymous json as class member and convert all to json in c#
how to put anonymous json as class member and convert all to json in c#

Time:01-15

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.

CodePudding user response:

you have to convert to JObject before you add new json string

JObject jo = JObject.FromObject(eventData);

jo["HealthInfo"] = jsonStringHealthInfo;

//or it could be (your question needs some details)
jo["HealthInfo"]=JObject.Parse(jsonStringHealthInfo);

StringContent   content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");

var response = await client.PostAsync(api, content))

CodePudding user response:

If you know all of the possible properties inside HealthInfo then you can create new class HealthInfo with nullable properties.

public class HealthInfo
{
    public string? SomeData { get; set; }
    public int? SomeOtherData { get; set; }
}

and then add nullable HealthInfo in your main class:

public class EventData
{
    public string deviceJobId { get; set; }
    public int eventID { get; set; }
    public long time_ms { get; set; }
    public HealthInfo? HealthInfo { get; set; }
    /// similar fields
}

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:

public class EventData
{
    public string deviceJobId { get; set; }
    public int eventID { get; set; }
    public long time_ms { get; set; }
    public object? HealthInfo { get; set; }
    /// similar fields
}
  • Related