To deserialize a JSON string in C# where the value within the JSON could be either a string or an integer, you can use the JsonConvert.DeserializeObject<T>
method with the JsonConverter
attribute.
For example, consider the following JSON string:
{
"id": 12345,
"name": "John Doe"
}
In this case, the id
field can either be a string or an integer. To deserialize this string in C#, you can define a class with the JsonConverter
attribute:
public class Person
{
[JsonProperty("id")]
[JsonConverter(typeof(IdConverter))]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class IdConverter : JsonConverter<int>
{
public override int ReadJson(JsonReader reader, Type objectType, int existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Integer)
{
return (int) reader.Value;
}
else if (reader.TokenType == JsonToken.String)
{
int.TryParse(reader.Value.ToString(), out int result);
return result;
}
throw new JsonReaderException($"Unexpected token type {reader.TokenType}");
}
public override void WriteJson(JsonWriter writer, int value, JsonSerializer serializer)
{
writer.WriteValue(value);
}
}
In the Person
class, the id
property is decorated with the [JsonConverter(typeof(IdConverter))]
attribute, which specifies that the IdConverter
should be used when deserializing this property.
The IdConverter
class is a custom converter that checks the token type of the JSON value and returns either the integer value or the parsed integer value if the token is a string.
To deserialize the JSON string using this class, you can use the following code:
string json = "{\"id\": 12345, \"name\": \"John Doe\"}";
Person person = JsonConvert.DeserializeObject<Person>(json);
This will deserialize the JSON string and assign the values to the Person
object, with the id
value being converted to an integer.
Asked: 2023-05-30 01:14:44 +0000
Seen: 1 times
Last updated: May 30 '23