我一直在製作一個自定義庫,用於將對象數組轉換爲json字符串併發布它。我最近遇到了一個我無法檢測到內部數組的問題。C#:無法檢查類型是否是數組
public static string ConvertArray(params object[] jsonData) {
if(jsonData.Length % 2 != 0) throw new ArgumentException(string.Format("Key \'{0}\' missing value", jsonData[jsonData.Length - 1]));
string json = "{";
for(int i = 0; i < jsonData.Length;) {
json += string.Format("\"{0}\":", jsonData[i++]);
if(jsonData[i] is string) {
Console.WriteLine("Found a string");
json += string.Format("\"{0}\",", jsonData[i++]);
} else if(jsonData[i].GetType().IsArray) {
Console.WriteLine("Found an internal array");
json += string.Format("{0},", ConvertArray(jsonData[i++]));
} else {
if(jsonData[i] is byte || jsonData[i] is sbyte || jsonData[i] is int || jsonData[i] is uint || jsonData[i] is short || jsonData[i] is ushort || jsonData[i] is long || jsonData[i] is ulong || jsonData[i] is float || jsonData[i] is double || jsonData[i] is bool || jsonData[i] is decimal) {
Console.WriteLine("Found a generic");
json += string.Format("{0},", jsonData[i++]);
} else if(jsonData[i] is char) {
Console.WriteLine("Found a char");
json += string.Format("\'{0}\',", jsonData[i++]);
} else {
Console.WriteLine("Found an object");
object work = jsonData[i++];
try {
MethodInfo workMethod = work.GetType().GetMethod("ToJsonString");
json += string.Format("{0},", workMethod.Invoke(work, new object[] { }));
} catch {
try {
using(MemoryStream memStr = new MemoryStream()) {
new BinaryFormatter().Serialize(memStr, work);
memStr.Seek(0, SeekOrigin.Begin);
using(StreamReader strReader = new StreamReader(memStr)) {
json += string.Format("\"{0}\",", strReader.ReadToEnd());
}
}
} catch {
throw new ArgumentException("The value for key \'{0}\' does not contain a public method ToJsonString and cannot be serialized");
}
}
}
}
}
return json + "}";
}
我一直在運行它:
string jsonString = JsonWebUtil.ConvertArray(new object[] {
"jsonrpc","2.0",
"method","generateIntegers",
"params",JsonWebUtil.ConvertArray(new object[] {
"apiKey", "<REDACTED>",
"n", 14,
"min", 0,
"max", 10,
}),
"id", 10461
});
而且我得到以下輸出:
{"jsonrpc":"2.0","method":"generateIntegers","params":"{"apiKey":"<REDACTED>","n":14,"min":0,"max":10,}","id":10461,}
不應該有一個報價約於內部數組尚未有。 當它通過我的代碼運行時,控制檯顯示它被檢測爲我聲明爲泛型。 我不知道爲什麼jsonData[i].getType().IsArray
沒有返回正確的值。
你在調試器中運行它嗎? 'jsonData [i] .getType()'在那裏顯示了什麼? –
另外你爲什麼要在循環內而不是在循環定義中遞增'i'? –
你正在重新發明車輪的任何原因。那裏已經有很多像樣的圖書館了... http://www.newtonsoft.com/json – Jeremy