You could probably create a custom JsonConverter
and apply it on your property.
Following is an example (NOTE: I haven't used this api before so it could probably be improved more, but following should give you a rough idea):
public class Person
{
[JsonConverter(typeof(IdToStringConverter))]
public long ID { get; set; }
public string Name { get; set; }
}
public class IdToStringConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jt = JValue.ReadFrom(reader);
return jt.Value<long>();
}
public override bool CanConvert(Type objectType)
{
return typeof(System.Int64).Equals(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}
}
Web API Action:
public Person Post([FromBody]Person person)
{
return person;
}
Request:
POST http://asdfasdf/api/values HTTP/1.1
Host: servername:9095
Connection: Keep-Alive
Content-Type: application/json
Content-Length: 42
{"ID":"1306270928525862400","Name":"Mike"}
Response:
HTTP/1.1 200 OK
Content-Length: 42
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 28 Jun 2013 17:02:18 GMT
{"ID":"1306270928525862400","Name":"Mike"}
EDIT:
if you do not want to decorate the property with an attribute, you could instead add it to the Converters collection. Example:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IdToStringConverter());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…