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.