How to deserialize a json to int? [duplicate]

-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 deserializes it 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 has the following error:

  

Unhandled Exception:
       Newtonsoft.Json.JsonReaderException: Could not convert string to integer: yyyy. Path 'ItemHome [0] .Icone', line 1, position 42.

How to convert values to int ?

    
asked by anonymous 27.03.2017 / 19:52

2 answers

7

In your test JSON, the properties Icone and Color are getting the value of aaaa . Of course, yyyy is not an integer value.

If you are sure that the value will be a text, change the type of properties to String , which 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 yyyy , you do not need to change the type of properties.

Ironically, the value of the property Texto that has type String , is receiving the value 1111 , which can be numeric.

Update

If you'd like, you can also create a CustomJsonConverter to try the conversion of type String to Int at the time of deserialization of JSON.

See the example below:

Converter:

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; }
}

In this way, it will always try to convert from String to int . If it does not, it will return the value of 0;

For details on how to convert String to int , see this answer.

For more details about CustomJsonConverter , see this answer or a Newton's own documentation.

    
27.03.2017 / 19:59
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 do not know what the real intention of this is, but if JSON is wrong, set the values in them, if it is the statement in your model that is wrong, change the properties of int to string . >

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

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

JSON Example

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'}]}";
    
27.03.2017 / 19:58