2 回答

TA貢獻1712條經驗 獲得超3個贊
我發現是什么問題...
為了在我的服務器/客戶端之間交換消息,我使用 JSON 形式。
服務器正在使用Go并使用該encoding/json包。
客戶端是 C# 中的Xamarin表單應用程序并使用Newtonsoft.json包。
一旦 JSON 被序列化,它就會以字符串的形式出現。但是,要在客戶端/服務器之間寫入/讀取,必須將其格式化為字節(C#byte[] && Go[]byte),因此我們必須將其jsonString轉換為字節數組。
用我的 Pseudo 看看這個轉換Emixam23:
// C#
Emixam23 == [69][0][109][0][105][0][120][0][97][0][109][0][50][0][51][0]
// Go
Emixam23 == [69][109][105][120][97][109][50][51]
這兩個數組表示我們的字符串Emixam23的字節數組,但是,它們是不同的。如您所見,我們有一個[0]用于 C# 部分,與 Go 部分不同。這[0]是左邊字節的符號。
等于 0 的字節表示'\0'C 語言的字符串的結尾。我認為 Go 的工作方式相同。如果我是對的,那么錯誤就是邏輯,當json.Decode() //go迭代我的字節數組時,它會走到最后,即'\0'. 所以 decode 在我的字節數組的第二種情況下停止,并嘗試用這個"{"無效的 JSON 字符串創建一個 JSON。
當然,對于 C# 部分也是如此。然后我創建了這兩個函數sign()和unsign()一個字節數組。
// for both, bytes[] is the byte array you want to convert and
// the lenght of this byte array when you call the function
public byte[] UnsignByteArray(byte[] bytes, int lenght)
{
int index = 0;
int i = 0;
var array = new byte[lenght / 2];
while (index < lenght)
{
array[i] = bytes[index];
index += 2;
i++;
}
return array;
}
public byte[] SignByteArray(byte[] bytes, int lenght)
{
int index = 0;
int i = 0;
var array = new byte[lenght * 2];
while (index < lenght)
{
array[i] = bytes[index];
i++;
index++;
array[i] = 0;
i++;
}
return array;
}
永遠不要忘記查看調試/打印雙方的每個數據,它可以提供幫助!
- 2 回答
- 0 關注
- 402 瀏覽
添加回答
舉報