将值从字符串转换为流时出错



我想序列化一个自定义对象:

public class MyCustomObject
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public List<HttpPostedFileBase> Files { get; set; }
    public MyCustomObject()
    {
        Files = new List<HttpPostedFileBase>();
    }
}

在json。为此,我使用自定义转换器:

public class HttpPostedFileConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stream = (Stream)value;
        using (var sr = new BinaryReader(stream))
        {
            var buffer = sr.ReadBytes((int)stream.Length);
            writer.WriteValue(Convert.ToBase64String(buffer));
        }
    }

我使用JsonSerializerSettings来序列化到json.net知道哪种类型实现(对于HttpPostedFileBase)

        var settings = new JsonSerializerSettings();
        settings.Converters.Add(new HttpPostedFileConverter());
        settings.TypeNameHandling = TypeNameHandling.Objects;

对象被正确序列化,但是我有这个序列化错误:

JsonSerializationException Error converting value "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDA

这是我序列化的对象的值:

{
  "$type": "ConsoleApplication1.MyCustomObject, ConsoleApplication1",
  "Name": "Test2",
  "Date": "2016-11-03T12:35:14.6020154+01:00",
  "Files": [
    {
      "$type": "System.Web.HttpPostedFileWrapper, System.Web",
      "ContentLength": 1024,
      "FileName": "Pannigale.jpg",
      "ContentType": "image/jpg",
      "InputStream": "/9j/4AAQ...KKAP//Z"
    }
  ]
}

反序列化有什么问题?

编辑我已经测试了一个类来测试…现在它工作了:

public class TestHttpFile : HttpPostedFileBase
{
    string fullFileName = @"C:PicturesSBK-1299-Panigale-S_2015_Studio_R_B01_1920x1080.mediagallery_output_image_[1920x1080].jpg";
    public override int ContentLength
    {
        get
        {
            return 1024;
        }
    }
    public override string FileName
    {
        get
        {
            return "Pannigale.jpg";
        }
    }
    public override string ContentType
    {
        get
        {
            return "image/jpg";
        }
    }
    public override Stream InputStream
    {
        get
        {
            return File.OpenRead(fullFileName);
        }
    }
}

在序列化中,我注意到以下区别:

 "$type": "ConsoleApplication1.TestHttpFile, ConsoleApplication1",
不是

 "$type": "System.Web.HttpPostedFileWrapper, System.Web",

但最后我不想创建一个包装器或其他…我不明白为什么它适用于这种类型,而不是HttpPostedFileWrapper .

为什么反序列化失败

简而言之:您试图反序列化的类型,即HttpPostedFileWrapper及其底层的HttpPostedFile,是不可公开构造的。

假设你的HttpPostedFileConverter实际上是一个流转换器,工作原理如下:

public class StreamConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Stream).IsAssignableFrom(objectType);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var bytes = serializer.Deserialize<byte[]>(reader);
        return new MemoryStream(bytes);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stream = (Stream)value;
        var bytes = stream.ReadAllBytesAndReposition();
        serializer.Serialize(writer, bytes);
    }
}
public static class StreamExtensions
{
    public static byte[] ReadAllBytesAndReposition(this Stream stream)
    {
        const int bufferSize = 4096;
        using (var ms = new MemoryStream())
        {
            byte[] buffer = new byte[bufferSize];
            int count;
            var position = stream.CanSeek ? stream.Position : (long?)null;
            while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                ms.Write(buffer, 0, count);
            if (position != null)
            {
                // Restore position
                stream.Position = position.Value;
            }
            return ms.ToArray();
        }
    }
}

在这种情况下,我可以为您的MyCustomObject类生成类似的JSON,假设我也在序列化器设置中设置TypeNameHandling = TypeNameHandling.Auto。但是,反序列化将失败,因为具体类型System.Web.HttpPostedFileWrapper只有一个构造函数,该构造函数接受HttpPostedFile。参考来源:

public class HttpPostedFileWrapper : HttpPostedFileBase {
    private HttpPostedFile _file;
    public HttpPostedFileWrapper(HttpPostedFile httpPostedFile) {
        if (httpPostedFile == null) {
            throw new ArgumentNullException("httpPostedFile");
        }
        _file = httpPostedFile;
    }

由于构造函数是公共的,所以Json。. NET将调用它,但由于JSON中没有名为httpPostedFile的属性,它将传递null作为该值,导致抛出ArgumentNullException

这给我们带来了下一个问题:HttpPostedFile没有公共构造函数。相反,要直接创建一个,您必须通过反射调用几个不同的Microsoft内部方法,如如何实例化HttpPostedFile所示。因此,即使您为HttpPostedFileWrapper创建了自定义JsonConverter,在其中构造必需的HttpPostedFile也是非常棘手的。Json。. NET当然不能自动完成。

那么,你有什么选择?

选项1:创建自己的HttpPostedFilesBase子类型

您可以创建自己的HttpPostedFilesBase的子类型,可以成功地序列化和反序列化,然后在序列化期间使用适当的JsonConverterHttpPostedFilesBase的所有实例映射到该类型。下面的类型MemoryHttpPostedFile是这样做的:

public sealed class MemoryHttpPostedFile : HttpPostedFileBase
{
    readonly string contentType;
    readonly string fileName;
    readonly MemoryStream inputStream;
    public MemoryHttpPostedFile(string contentType, string fileName, [JsonConverter(typeof(StreamConverter))] MemoryStream inputStream)
    {
        if (inputStream == null)
            throw new ArgumentNullException("inputStream");
        this.contentType = contentType;
        this.fileName = fileName;
        this.inputStream = inputStream;
    }
    public override int ContentLength { get { return (int)inputStream.Length; } }
    public override string ContentType { get { return contentType; } }
    public override string FileName { get { return fileName; } }
    [JsonConverter(typeof(StreamConverter))]
    public override Stream InputStream { get { return inputStream; } }
    //TODO: implement SaveAs()
    public override void SaveAs(string filename)
    {
        // Implement based on HttpPostedFile.SaveAs()
        // https://referencesource.microsoft.com/#System.Web/HttpPostedFile.cs,678e7f8bc95c149f
        throw new NotImplementedException();
    }
}
public class HttpPostedFileBaseConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(HttpPostedFileBase).IsAssignableFrom(objectType)
            && !typeof(MemoryHttpPostedFile).IsAssignableFrom(objectType);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var postedFile = (HttpPostedFileBase)value;
        // Save position
        var wrapper = new MemoryHttpPostedFile(postedFile.ContentType, postedFile.FileName, new MemoryStream(postedFile.InputStream.ReadAllBytesAndReposition()));
        serializer.Serialize(writer, wrapper);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var wrapper = serializer.Deserialize<MemoryHttpPostedFile>(reader);
        return wrapper;
    }
}

由于HttpPostedFilesBase的所有子类型都映射到MemoryHttpPostedFile,因此不再需要设置TypeNameHandling.Auto。注意,我使用StreamConverterStreamExtensions从前面的这个答案。

将转换器添加到如下设置中:

var settings = new JsonSerializerSettings
{
    Converters = new JsonConverter[] { new HttpPostedFileBaseConverter() },
    Formatting = Formatting.Indented,
};

选项2:实际序列化和反序列化HttpPostedFileWrapper

要做到这一点,我们需要使用相当复杂和"黑客"的代码,从这个答案如何通过paracycle实例化HttpPostedFile,像这样:

public class HttpPostedFileBaseConverter : JsonConverter
{
    class HttpPostedFileSurrogate
    {
        public string ContentType { get; set; }
        public string FileName { get; set; }
        public byte[] InputStream { get; set; }
    }
    public override bool CanConvert(Type objectType)
    {
        return typeof(HttpPostedFileBase).IsAssignableFrom(objectType);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var wrapper = (HttpPostedFileWrapper)value;
        // Save position
        var surrogate = new HttpPostedFileSurrogate
        {
            ContentType = wrapper.ContentType,
            FileName = wrapper.FileName,
            InputStream = wrapper.InputStream.ReadAllBytesAndReposition(),
        };
        serializer.Serialize(writer, surrogate);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var surrogate = serializer.Deserialize<HttpPostedFileSurrogate>(reader);
        var file = HttpPostedFileExtensions.ConstructHttpPostedFile(surrogate.InputStream, surrogate.FileName, surrogate.ContentType);
        return new HttpPostedFileWrapper(file);
    }
}
public static class HttpPostedFileExtensions
{
    public static HttpPostedFile ConstructHttpPostedFile(byte[] data, string filename, string contentType)
    {
        // Adapted from https://stackoverflow.com/questions/5514715/how-to-instantiate-a-httppostedfile/5515134#5515134
        // Get the System.Web assembly reference (they seem to be in different assemblies in different versions of .Net
        var assemblies = new[] { typeof(HttpPostedFile).Assembly, typeof(HttpPostedFileBase).Assembly };
        // Get the types of the two internal types we need
        Type typeHttpRawUploadedContent = assemblies.Select(a => a.GetType("System.Web.HttpRawUploadedContent")).Where(t => t != null).First();
        Type typeHttpInputStream = assemblies.Select(a => a.GetType("System.Web.HttpInputStream")).Where(t => t != null).First();
        // Prepare the signatures of the constructors we want.
        Type[] uploadedParams = { typeof(int), typeof(int) };
        Type[] streamParams = { typeHttpRawUploadedContent, typeof(int), typeof(int) };
        Type[] parameters = { typeof(string), typeof(string), typeHttpInputStream };
        // Create an HttpRawUploadedContent instance
        object uploadedContent = typeHttpRawUploadedContent
          .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, uploadedParams, null)
          .Invoke(new object[] { data.Length, data.Length });
        // Call the AddBytes method
        typeHttpRawUploadedContent
          .GetMethod("AddBytes", BindingFlags.NonPublic | BindingFlags.Instance)
          .Invoke(uploadedContent, new object[] { data, 0, data.Length });
        // This is necessary if you will be using the returned content (ie to Save)
        typeHttpRawUploadedContent
          .GetMethod("DoneAddingBytes", BindingFlags.NonPublic | BindingFlags.Instance)
          .Invoke(uploadedContent, null);
        // Create an HttpInputStream instance
        object stream = (Stream)typeHttpInputStream
          .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, streamParams, null)
          .Invoke(new object[] { uploadedContent, 0, data.Length });
        // Create an HttpPostedFile instance
        HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
          .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null)
          .Invoke(new object[] { filename, contentType, stream });
        return postedFile;
    }
}

注意我使用StreamExtensions从前面的这个答案。这个版本的HttpPostedFileBaseConverter也会像往常一样被添加到JsonSerializerSettings.Converters中。

(老实说,我不推荐这种解决方案,因为它太依赖于Microsoft的HttpPostedFile实现的内部文档,在以后的版本中很容易改变。)

实际上有两个独立的问题。

流转换器

我想序列化一个自定义对象…在json。为此,我使用自定义转换器…

虽然你叫它HttpPostedFileConverter,张贴的代码表明,它所做的一切是将StreamBase64编码的string。所以让我们以不同的方式调用它并实现所有方法:

public class StreamConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Stream).IsAssignableFrom(objectType);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new MemoryStream(Convert.FromBase64String((string)reader.Value));
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stream = (Stream)value;
        using (var sr = new BinaryReader(stream))
        {
            var buffer = sr.ReadBytes((int)stream.Length);
            writer.WriteValue(Convert.ToBase64String(buffer));
        }
    }
}

它将用于InputStream成员序列化/反序列化,因此在这两个地方都将使用:

settings.Converters.Add(new StreamConverter());

对于序列化,这就是所需要的。现在是棘手的部分。

反序列化HttpPostedFileBase实例

但最后我不想创建一个包装器或其他…我不明白为什么它适用于这种类型,而不是HttpPostedFileWrapper

问题是用于序列化的HttpPostedFileWrapper没有无参数构造函数。实际上,唯一可用的构造函数具有以下签名:

public HttpPostedFileWrapper(
    HttpPostedFile httpPostedFile
)

可以看到,它需要HttpPostedFile。但HttpPostedFile根本没有公共构式。

所以,不管你想不想,除了创建一个自定义类来反序列化HttpPostedFileBase实例之外,你别无选择。

让我们这样做:

public class CustomHttpPostedFile : HttpPostedFileBase
{
    [JsonProperty("ContentLength")]
    private int contentLength;
    [JsonProperty("FileName")]
    private string fileName;
    [JsonProperty("ContentType")]
    private string contentType;
    [JsonProperty("InputStream")]
    private Stream inputStream;
    [JsonIgnore]
    public override int ContentLength { get { return contentLength; } }
    [JsonIgnore]
    public override string FileName { get { return fileName; } }
    [JsonIgnore]
    public override string ContentType { get { return contentType; } }
    [JsonIgnore]
    public override Stream InputStream { get { return inputStream; } }
    public override void SaveAs(string filename)
    {
        using (var output = File.Create(fileName))
            InputStream.CopyTo(output);
    }
}

但这还不够。为了让反序列化器使用这个类而不是HttpPostedFileWrapper,您需要一个Json中的CustomCreationConverter。. NET使用CustomCreationConverter反序列化示例:

public class HttpPostedFileBaseConverter : CustomCreationConverter<HttpPostedFileBase>
{
    public override HttpPostedFileBase Create(Type objectType)
    {
        return new CustomHttpPostedFile();
    }
}

,只在反序列化时使用:

settings.Converters.Add(new StreamConverter());
settings.Converters.Add(new HttpPostedFileBaseConverter());

,一切都会正常。

概括一下,您遇到的主要问题是由于在对象内部使用抽象类及其具体实现所引起的,您无法控制这些实现,并且没有提供反序列化的方法(因为它根本不是为序列化而设计的)。因此,值得庆幸的是,这个解决方案是存在的,只是需要花费一些编写自定义代码的成本。

HttpPostedFileBase是一个抽象类,HttpPostedFile是其具体实现。当您在ASP中从用户获得文件上传时。Net,它的类型实际上是HttpPostedFile。因此,您正在寻找的包装器已经存在,您不必编写一个。

var file = (HttpPostedFile) Request.Files[0];

似乎您需要存储的不是严格的HttpPostedFileHttpPostedFileBase,而是具有大小,mime类型,文件名和流等属性的任意类作为字节数组。如果要将对象存储在数据库中,这样做更有意义。为什么不创建一个类并从HttpPostedFile复制属性呢?

编辑

似乎json不能反序列化到HttpPostedFile,因为它没有构造函数。你的选择是要么写一个继承HttpPostedFileBase的类,要么写一个新类。

下面是我用来测试的JsonConverter:
public class StreamConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stream = (Stream)value;
        using (var sr = new BinaryReader(stream))
        {
            var buffer = sr.ReadBytes((int)stream.Length);
            writer.WriteValue(Convert.ToBase64String(buffer));
        }
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var str = reader.ReadAsString();
        var stream = new MemoryStream();
        using (var sr = new BinaryWriter(stream))
        {
            sr.Write(Convert.FromBase64String(str));
        }
        return stream;
    }
    public override bool CanConvert(Type objectType)
    {
        return typeof(Stream).IsAssignableFrom(objectType);
    }
}

相关内容

  • 没有找到相关文章

最新更新