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.
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
– Jonas Vieira
That rollback wasn’t smart at all. You know the
int.Parse
and theint.TryParse
?– Bruno Costa
Why did you reverse my edit?
– Jéf Bueno