How to deserialize a json to int?

Asked

Viewed 558 times

-5

I have a test json to see if my implementation worked in my code:

string json = @"{'ItemHome':[{'Texto':'111','Icone':'aaaa','Color':'aaaa'}, {'Texto':'111','Icone':'aaaa','Color':'aaaa'}, {'Texto':'111','Icone':'aaaa','Color':'aaaa'}, {'Number':'531141884','ContactName':'ftftft'}]}";

and deserializo him as follows:

Model Dados = JsonConvert.DeserializeObject<Model>(json);

and my model:

public class Model
{
    public List<ModelHome> ItemHome { get; set; }
}

public class ModelHome
{
    public string Texto { get; set; }
    public int Icone { get; set; }
    public int Color { get; set; }
}

But it presents the following error:

Unhandled Exception:
Newtonsoft.Json.Jsonreaderexception: Could not Convert string to integer: aaaa. Path 'Itemhome[0]. Icone', line 1, position 42.

How to convert values to int?

  • As I said "I have a test json to see if my implementation worked in my code:" I just need to know how to convert a value to int

  • 4

    That rollback wasn’t smart at all. You know the int.Parse and the int.TryParse?

  • 2

    Why did you reverse my edit?

2 answers

7


In your JSON testing, the properties Icone and Color are receiving the value of aaaa. Logically, aaaa is not an integer value.

If you are sure the value will be text, change the type of properties to String, that should solve your problem.

public class ModelHome
{
    public string Texto { get; set; }
    public string Icone { get; set; }
    public string Color { get; set; }
}

If you pass numeric values instead of aaaa, no need to change the type of properties.

Ironically, the value of the property Texto that has the type String, is getting the value 1111, which may be numerical.

Updating

If you want, you can also create a Customjsonconverter to try to perform the type conversion String for Int at the time of JSON deserialisation.

See the example below:

Convert:

public class StringToIntConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(int?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType == JsonToken.Integer)
            return reader.Value;

        if (reader.TokenType == JsonToken.String)
        {
            if (string.IsNullOrEmpty((string)reader.Value))
                return null;
            int num;
            //Tenta converter o valor
            if (int.TryParse((string)reader.Value, out num))
            {
                return num;
            }
            //Retorna 0
            else
            {
                return 0;
            }

        }
        throw new JsonReaderException(string.Format("Unexcepted token {0}", reader.TokenType));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }
}

And in your Model, just put the note:

public class ModelHome
{
    public string Texto { get; set; }
    [JsonConverter(typeof(StringToIntConverter))]
    public int Icone { get; set; }
    [JsonConverter(typeof(StringToIntConverter))]
    public int Color { get; set; }
}

This way he will always try to convert from String for int. If you cannot, you will return the value of 0;

For more details on how to convert String for int, see this response.

For more details about the CustomJsonConverter, see this answer or the own documentation from Newtonsoft.

4

The error is very clear. The properties Icone and Color are declared as int and in JSON they have a string as value.

I don’t know what the real purpose of this is, but if JSON is wrong, arrange the values in them, if the statement in your model is wrong, change the properties of int for string.

Another problem is that the last item on the list does not have the correct properties, that’s right?

public class ModelHome
{
    public string Texto { get; set; }
    public string Icone { get; set; }
    public string Color { get; set; }
}

Example from JSON

string json = @"{'ItemHome': [{'Texto':'111','Icone':'1','Color':'2'}, 
                              {'Texto':'111','Icone':'2','Color':'1'}, 
                              {'Texto':'111','Icone':'1','Color':'3'}, 
                              {'Number':'531141884','ContactName':'ftftft'}]}";
  • As I said "I have a test json to see if my implementation worked in my code:" I just need to know how to convert a value to int

Browser other questions tagged

You are not signed in. Login or sign up in order to post.