2012-02-20 94 views
2
参数

这里是我的JSON:字节[]作为一个JSON

byte[] attachmentBytes = ZipToBase64(); 
string json = "{ \"method\": \"Bug.add_attachment\", " + 
       " \"params\": [ {" + 
         " \"ids\": " + "    \"" + "25" +"\", " + 
         " \"data\": " + "    \"" + attachmentBytes + "\", " + 
         " \"file_name\": " + " \"BugReport.zip\", " + 
         " \"Bugzilla_login\": " + " \"[email protected]\", " + 
         " \"Bugzilla_password\": " + "    \"mypassword\", " + 
         " \"summary\": " + "    \"blah blah\", " + 
         " \"content_type\": " + " \"application/octet-stream\" " + 
           " } ], " + 
          "\"id\": 1" 
       + "}"; 

public static byte[] ZipToBase64() 
    { 
     string filePath = @"C:\Users\John\Desktop\SomeArchive.zip"; 
     if (!string.IsNullOrEmpty(filePath)) 
     { 
      FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); 
      byte[] filebytes = new byte[fs.Length]; 
      fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); 
      string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks); 
      string encoded = encodedData; 
      return filebytes; 
     } 
     return null; 
    } 

我认为这个问题是在attachmentBytes一部分,因为它是一个byte []。如何在json中传递byte []?

代码是用C#编写的。

+0

您可以将每个字节转换为base64string,然后在接收端将其转换回来。 – 2012-02-20 15:16:28

回答

3

看来你试图连接一个字节[]字符串。这是行不通的。我猜你得到的错误是关于这个连接的编译错误,对吧?

而不是返回字节[],返回Convert.ToBase64String返回的base64字符串。您可以在JSON中嵌入该字符串。

虽然我们谈到这个问题,但您可以通过简单地拨打File.ReadAllBytes(filePath)来大幅缩短文件阅读范围,因为它封装了所有文件流业务,因此您不必这样做。

+0

但现在我得到错误“无法解析JSON数据”。 Bug.add_attachment方法的输入字节[]用于数据。 – 2012-02-20 15:21:28

+0

用我的代码,我没有得到错误,但我试图上传的zip文件已损坏。 – 2012-02-20 15:22:49

+1

首先 - 是否有一个原因,你不使用JSON.NET等JSON库,这将节省你自己序列化对象的额外工作?其次 - 谁抛出这个异常?你的代码?您要发送JSON的服务?这一切发生在哪里?向我们展示发生异常的代码和一些上下文。 – 2012-02-20 15:23:43

0

更改ZipToBase64因此它将返回String而不是byte array

public static string ZipToBase64() 
{ 
    string filePath = @"C:\Users\John\Desktop\SomeArchive.zip"; 
    if (!string.IsNullOrEmpty(filePath)) 
    { 
     FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); 
     byte[] filebytes = new byte[fs.Length]; 
     fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); 
     return Convert.ToBase64String(filebytes, 
             Base64FormattingOptions.InsertLineBreaks); 
    } 
     return null; 
} 
+0

但现在我得到错误“无法解析JSON数据”。 Bug.add_attachment方法的输入字节[]用于数据。 – 2012-02-20 15:21:50

+0

用我的代码,我没有得到错误,但我试图上传的zip文件已损坏。 – 2012-02-20 15:23:21