使用base64编码的文件附件反序列化json文件

时间:2017-06-01 15:11:27

标签: c# json json.net base64

我正在尝试使用JSON.NET从JSON文件反序列化base64文件附件。我可以使用以下代码反序列化数据,但我不知道如何解码base64文件。请告诉我。

Sample JSON file
-----------------
PostData: {
  "Main":{
     "date1": "14-JAN-2016",
     "summary": "summary test",
     "Details":[{
       "first": "test",
       "last": "last test",
        },
      ]}
     "attachments":[        {
       "title": "Report1.pdf",
       "file_name": "Report1.pdf",
       "file_content_type": "application/pdf",
       "file_format": "binary",
       "file_data": "JVBERi0xLjQNCjUgMCBvYmoNCjw8DQovVHlwZSAvWE9iamVjdA0KL1N1YnR5cGUg
        MSAwIFIvSW5mbyAxMjYgMCBSL0lEWzw0NTQ3QjRFREZBNjk2NDQ4QjhBNUU4MUQw
        QkU4MkVDMD48NDU0N0I0RURGQTY5NjQ0OEI4QTVFODFEMEJFODJFQzA+XSAvUHJl
        diAxMTI3OTI5L1hSZWZTdG0gMTEyNjMxNj4+DQpzdGFydHhyZWYNCjExNDAyNTEN
        CiUlRU9G",
        },
        {
       "title": "src.txt",
       "file_name": "src.txt",
       "file_content_type": "text/plain",
       "file_format": "text",
       "file_data": "bm5gLDJ9NC1DNFkpN20y4tLmM0",
        },
  ]}
}

Program.cs的

var json = System.IO.File.ReadAllText("postData.json");
var myJsonObject = JsonConvert.DeserializeObject<PostData>(json);
    public class PostData
    {
        public Main main { get; set; }
    }

    public class Main
    {

        public string date1 { get; set; }
        public string summary { get; set; }
        public List<Details> details { get; set; }
    }

  public class Details
    {
        public string first { get; set; }
        public string last { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

正如其Serialization Guide所述,Json.NET自动(de)将Byte []数组序列化为Base64字符串。因此,在cleaning up your JSON之后,您可以将其上传到http://json2csharp.com/以自动生成类,然后file_data属性修改为类型byte [] 结果如下所示:

public class Detail
{
    public string first { get; set; }
    public string last { get; set; }
}

public class Main
{
    public string date1 { get; set; }
    public string summary { get; set; }
    public List<Detail> Details { get; set; }
}

public class Attachment
{
    public string title { get; set; }
    public string file_name { get; set; }
    public string file_content_type { get; set; }
    public string file_format { get; set; }
    public byte [] file_data { get; set; }
}

public class PostData
{
    public Main Main { get; set; }
    public List<Attachment> attachments { get; set; }
}

现在您可以按如下方式反序列化:

var myJsonObject = JsonConvert.DeserializeObject<RootObject>(json);

然后,要将反序列化的字节数组保存到磁盘,您可以使用File.WriteAllBytes()

执行以下操作
foreach (var attachment in myJsonObject.PostData.attachments ?? Enumerable.Empty<Attachment>())
{
    File.WriteAllBytes(attachment.file_name, attachment.file_data);
}