Search code examples
c#apache-kafkaavroconfluent-platform

Unable to cast Generic record to object


Hi I have below model in c#. These are Avro files.

public ProductMessageEvents GetValue(TestPayload parameter)
{
    return new ProductMessageEvents()
        {
            Metadata = new KafkaProductEvent.Metadata
                {
                    Timestamp = "test",
                    Environment = "test"
                },
            Product = new KafkaProductEvent.Product
                {
                    AgeGrading = "test",
                    KeycodeType = "type1",
                    FamilyTree = new KafkaProductEvent.FamilyTree
                        {
                            Class = new KafkaProductEvent.CodeNamePair
                                {
                                    Code = "test code",
                                    Name = "test name"
                                }
                        },
                    DssProduct = new KafkaProductEvent.DssProduct
                        {
                            DocumentStatus = "active"
                        }
                      Options = new Option[]
            {
              new Option
              {
                PrimaryColour = new CodeNamePair
                {
                  Name = "White",
                },
                SecondaryColour = new CodeNamePair
                {
                  Name = "red",
                }
              },
              new Option
              {
                PrimaryColour = new CodeNamePair
                {
                  Name = "White",
                }
              },
                },
            Version = "latestVersion"
        };
    }
}

If I try to access the below value it works.

 object ageGrading = ((GenericRecord)response.Message.Value["Product"])["AgeGrading"];

If I try to access the below value, then it throws

object familyTree = ((GenericRecord)response.Message.Value["Product"])["FamilyTree"]["Class"]["Code"];

It throws error Cannot apply indexing with [] to an expression of type object

Option data

Can someone help me to identify this error? Any help would be appreciated. Thanks.


Solution

  • You are casting this object to a GenericRecord ((GenericRecord)response.Message.Value["Product"]) but it returns this ((GenericRecord)response.Message.Value["Product"])["FamilyTree"] as an object. You'll need to cast each level to GenericRecord to get to it's properties.

    ((GenericRecord)((GenericRecord)((GenericRecord)response.Message.Value["Product"])["FamilyTree"])["Class"])["Code"]