Reputation: 11454
I am deserializing JSON using Json.Net. The incoming JSON data has fields that represent currency that I would like deserialized to a decimal type field in my typed object. The problem is that the incoming data has no decimal point, it is always in cents, so 1000 would be mean 10 dollars, or 10.00. Is there a way to handle this in Json.Net?
Upvotes: 2
Views: 95
Reputation: 87228
You can use a JsonConverter
class that would do that translation for you. The code below is a possible implementation of this.
public class Program
{
public class Product
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value"), JsonConverter(typeof(NoDecimalPointConverter))]
public decimal Value { get; set; }
public override string ToString()
{
return string.Format("{0}-{1}", Name, Value);
}
}
class NoDecimalPointConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(decimal) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
long longValue = serializer.Deserialize<long>(reader);
return ((decimal)longValue) / 100;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
long longValue = (long)((decimal)value * 100);
serializer.Serialize(writer, longValue);
}
}
static void Main(string[] args)
{
string JSON = "[{'name':'bread','value':256},{'name':'milk','value':299}]".Replace('\'', '\"');
var products = JsonConvert.DeserializeObject<List<Product>>(JSON);
Console.WriteLine(string.Join(", ", products));
}
}
Upvotes: 2