【问题标题】:Why cant I access this dynamic property from deserialized Newtonsoft json为什么我不能从反序列化的 Newtonsoft json 访问这个动态属性
【发布时间】:2020-07-09 09:24:19
【问题描述】:

我正在将一个对象从一个微服务发送到另一个微服务,因此已经序列化了一个包含此属性的对象

public class Template 
{
    public int Id { get; set; }
    public string FileFormat { get; set; }
}

我不想在收到此消息的其他微服务中建模TemplateDTO,因为我只需要访问其中一个模板属性。此外,稍后在将其发送到不同的微服务时,我确实需要Id,这就是我需要它的原因,否则我可以只发送一个字符串道具。这是我的 DTO 中的属性:

public dynamic Template { get; set; }

反序列化有效,但我似乎不能

templateObj.FileFormat;   //templateObj is equal to reportJson.Template

这是对象在调试时的样子:

尝试从对象访问任何内容时出现此错误:

错误 CS1061:“object”不包含“FileFormat”的定义,并且找不到接受“object”类型的第一个参数的可访问扩展方法“FileFormat”(您是否缺少 using 指令或程序集引用? )

我在这里错过了什么?

编辑

序列化对象有多个属性,其中之一是模板。当我在另一个微服务中反序列化它时:

var reportJson = JsonConvert.DeserializeObject<ReportDTO>(serializedMessage);

我遇到了上述问题。

ReportDTO 如下所示:

public class ReportDTO
{
    public dynamic Template { get; set; }

    ... 
}

【问题讨论】:

  • 您需要分享更多代码。您有名为 Template 的类。但是你有一个动态属性。这个属性是在哪里声明的?您如何进行 JSON 反序列化? templateObj 的数据类型是什么?您还可以分享您尝试反序列化的示例 JSON 吗?
  • @ChetanRanpariya templateObj 只是反序列化消息后的动态对象。 Template 的类在微服务 A 中,动态属性在微服务 B 的 ReportDTO 中。
  • 感谢您分享详细信息。当您尝试访问 reportJson.Template.FileFormat 时会发生什么?
  • 这是我从中得到的错误。 templateObj 等于 reportJson.Template

标签: c# serialization json.net deserialization


【解决方案1】:

假设你有这些课程:

public class Report
{
    public Template Template { get; set; }
}

public class Template
{
    public int Id { get; set; }
    public string FileFormat { get; set; }
}

public class ReportDto
{
    public dynamic Template { get; set; }
}

那么你应该像这样序列化和反序列化:

        var report = new Report
        {
            Template = new Template { Id = 5, FileFormat = "PDF" }
        };
        var serializedReport = JsonConvert.SerializeObject(report);

        var deserializedReport = JsonConvert.DeserializeObject<ReportDto>(serializedReport);
        Console.WriteLine(deserializedReport.Template.FileFormat); // Output : PDF

你的错误是你使用 deserializedReport.FileFormat 而不是 deserializedReport.Template.FileFormat

【讨论】:

  • 对不起,应该更详细。序列化对象不仅包含模板。还有更多属性,其中一个属性是模板。我确实想对整个消息使用静态 DTO,而不是 Template。
  • 我的问题中的 templateObj 已经等于 deserializedReport.Template
  • 一切都在问题之中。我已经把反序列化放在那里了。唯一的额外位是templateObj = reportsJson.Template
【解决方案2】:

我想通了。当我通过反序列化它时结果是

JsonConvert.DeserializeObject<T>(serializedObj);

由于模板是动态的,它会自动转换为JObject,所以我必须使用类似的东西来获取值:

(string)((JObject)templateObj)["FileFormat"]

输出:“PDF”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多