您可能可以创建一个自定义JsonConverter
并将其应用于您的财产。
以下是一个示例(注意:我以前没有使用过这个 api,所以它可能会得到更多改进,但下面应该给你一个粗略的想法):
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 操作:
public Person Post([FromBody]Person person)
{
return person;
}
要求:
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"}
回复:
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"}
编辑:
如果您不想用属性装饰属性,则可以将其添加到 Converters 集合中。例子:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IdToStringConverter());