2012-02-20 96 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