简体   繁体   中英

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

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.

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))

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
}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM