繁体   English   中英

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

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

我有一个定义明确的 class,用于在 HTTP 请求中作为 JSON 正文发送。

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

现在我必须再添加一个名为HealthInfo的字段。 这个新的HealthInfo的值是从某个文件读取的嵌套 JSON。 这个 JSON 文件的字段会不时更改,并且不能保证某些字段始终存在。

我不想读取/修改它的任何值,只需要将此EventData发布为 json 作为 HTTP 请求的一部分。

那么如何正确添加HealthInfo呢?

我试图将HealthInfo作为字符串,object 被双重序列化。

在添加新的 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))

如果您知道 HealthInfo 中所有可能的属性,那么您可以创建具有可为空属性的新 class HealthInfo

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

然后在您的主 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
}

但是,如果您不确定要获取哪种数据并希望避免双重序列化,只需将 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
}

您可以使用 C# 反射。 (TypeBuilder.DefineProperty Method) 实际上你必须在运行时给 class 添加 prop。

查看完整信息

https://learn.microsoft.com/

暂无
暂无

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

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