简体   繁体   English

如何将匿名json作为class成员并在c#中全部转换为json

[英]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.我有一个定义明确的 class,用于在 HTTP 请求中作为 JSON 正文发送。

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 .现在我必须再添加一个名为HealthInfo的字段。 The value of this new HealthInfo is a nested JSON read from some file.这个新的HealthInfo的值是从某个文件读取的嵌套 JSON。 The fields of this JSON file change from time to time, and there is no guarantee that some fields will always be present.这个 JSON 文件的字段会不时更改,并且不能保证某些字段始终存在。

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.我不想读取/修改它的任何值,只需要将此EventData发布为 json 作为 HTTP 请求的一部分。

Then how to add HealthInfo correctly?那么如何正确添加HealthInfo呢?

I tried to put HealthInfo as string and object is getting double serialized.我试图将HealthInfo作为字符串,object 被双重序列化。

you have to convert to JObject before you add new json string在添加新的 json 字符串之前,您必须转换为 JObject

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.如果您知道 HealthInfo 中所有可能的属性,那么您可以创建具有可为空属性的新 class HealthInfo

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

and then add nullable HealthInfo in your main class:然后在您的主 class 中添加可为空的 HealthInfo:

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:但是,如果您不确定要获取哪种数据并希望避免双重序列化,只需将 HealthInfo 作为 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.您可以使用 C# 反射。 (TypeBuilder.DefineProperty Method) In fact you must add prop to the class in run time. (TypeBuilder.DefineProperty Method) 实际上你必须在运行时给 class 添加 prop。

see full information at查看完整信息

https://learn.microsoft.com/ https://learn.microsoft.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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