Search code examples
c#serializationjson.netdeserialization

Why cant I access this dynamic property from deserialized Newtonsoft json


I am sending an object from one microservice to another so have serialized an object that contains this property

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

I don't want to model a TemplateDTO in the other microservice that gets this message as I only need to access one of the Template properties. Also, I do need the Id later on when sending this to a different microservice that's why I need it otherwise I could just send a single string prop. This is the property in my DTO:

public dynamic Template { get; set; }

The deserialization works but I can't seem to

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

This is what the object looks like in debug:

I get this error when trying to access anything from the object:

error CS1061: 'object' does not contain a definition for 'FileFormat' and no accessible extension method 'FileFormat' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

What am I missing here?

EDIT

The serialized object has multiple properties and one of them is Template. When I deserialize it in another microservice:

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

I get the above issues.

The ReportDTO looks like this:

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

    ... 
}

Solution

  • I figured it out. Turns out when I deserialize it through

    JsonConvert.DeserializeObject<T>(serializedObj);
    

    Since the Template is dynamic it gets converted into a JObject automatically so I have to use something like this to get the value:

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

    Output: "PDF"