Ask Your Question
2

How can C# json.deserialize be used in cases where the value within the json may be either a string or an integer?

asked 2023-05-30 01:14:44 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-30 01:15:01 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-30 01:14:44 +0000

Seen: 1 times

Last updated: May 30 '23