mvc6 json反序列化

时间:2016-08-31 02:01:48

标签: c# json asp.net-core asp.net-core-mvc

我正在使用Asp.Net Core编写自定义JSON Guid序列化/反序列化,但我无法修改默认反序列化以添加我的代码。

我用这个序列化了: Startup.cs

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc().AddJsonOptions(options => {
				options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
				options.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;			
	
				options.SerializerSettings.Converters.Insert(0, new GuidConverter());  	    	
	
});
 }

但似乎这只适用于出站邮件,而不是入站邮件。

供参考,转换器代码如下:

public class GuidConverter : JsonConverter {
    public override bool CanConvert(Type objectType) {
        return objectType == typeof(Guid) || objectType == typeof(Guid?);
    }

    public override bool CanRead { get { return true; } }
    public override bool CanWrite { get { return true; } }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        if (null == value) {
            writer.WriteNull();
            return;
        }
        var nullableGuid = value as Guid?;

        Guid guid;
        if (nullableGuid.HasValue) {
            guid = nullableGuid.Value;
        } else {
            guid = (Guid)value;
        }

        writer.WriteValue(guid.ToShort());
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        if (reader.TokenType == JsonToken.Null) {
            return null;
        }
        if (reader.TokenType != JsonToken.String) {
            throw new Exception(String.Format("Unexpected token parsing Guid. Expected String, got {0}.", reader.TokenType));
        }

        var guid = GuidUtility.FromShort((string)reader.Value);

        return guid;
    }
}

0 个答案:

没有答案