goodkidbadmAArky
goodkidbadmAArky

Reputation: 43

Converting a JSON to a C# object, but JSON has duplicate property names with different value types

I'm using C#, netcoreapp3.1 along with the Newtonsoft.Json NuGet.

I have a class set up like so (simplified):

    public class ButtonRequest
    {
        public Message message { get; set; }
    }
    public class Message
    {
        public Block[] blocks { get; set; }
    }
    public class Block
    {
        public Text text { get; set; }
        public BlockElement[] elements { get; set; }
    }
    public class BlockElement
    {
        public string type { get; set; }
        public string value { get; set; }
        public string text { get; set; }
    }

When I receive a JSON, I convert it to an object like so:

ButtonRequest button = JsonConvert.DeserializeObject<ButtonRequest>(request.payload);

The issue that I'm running into is that the JSON I'm trying to parse has property values that are named the same but store different value types. You can see that in the following picture. In block [1} -> element[2] the property name "text" stores three properites. Where as in block[3] -> element[0] the property name "text" just stores a string.

enter image description here

When using my above method of converting the JSON to object, it fails because it does not know how to handle the two different instances of "text." Since this is a web application, I'm not sure exactly why it fails. All I know is that the information is not stored correctly. Thanks for any help.

Upvotes: 0

Views: 143

Answers (1)

goodkidbadmAArky
goodkidbadmAArky

Reputation: 43

I found an answer. By declaring text as an object, I am able to avoid any errors. Like so:

    public class BlockElement
    {
        public string type { get; set; }
        public string value { get; set; }
        public object text { get; set; }
    }

Then, when I want to use the string property value, I just use text.ToString()

Upvotes: 1

Related Questions