Search code examples
c#jsonserializationjson-deserialization

C# Json - JSONproperty of Various Data Types. .net 3.5


Trying to figure out how to Serialize or Deserialize (JSON) an object, that has a value property that can be a bool, number, or string.

"object": {
  "id":"someID",
  "value": -10 or true or "someString"
}

I expect I will need to use JSONConvert, however I am not really finding how to do this with a Primitive DataType, all I can find is converting between a single object or an array of said object. This seems like it should be straight forward, for whatever reason, I just can't figure it out.


Solution

  • You can convert to object datatype, it can ben a number, string, list... You just have to handle it carefully.

        public class Object
        {
            [JsonProperty("id")]
            public string Id { get; set; }
            [JsonProperty("value")]
            public object Value { get; set; }
        }