2013-09-26 95 views
2

在我的代碼,我有一個創建JSON請求我的比特幣服務器功能:Newtonsoft JSON - 陣列不序列化正確

public static JObject InvokeMethod(string sMethod, params object[] parameters) 
{ 
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url); 
    webRequest.Credentials = Credentials; 

    webRequest.ContentType = "application/json-rpc"; 
    webRequest.Method = "POST"; 

    JObject joe = new JObject(); 
    joe["jsonrpc"] = "1.0"; 
    joe["id"] = "1"; 
    joe["method"] = sMethod; 

    if (parameters != null) 
    { 
     if (parameters.Length > 0) 
     { 
      JArray props = new JArray(); 
      foreach (var p in parameters) 
      { 
       props.Add(p); 
      } 
      joe.Add(new JProperty("params", props)); 
     } 
    } 

    string s = JsonConvert.SerializeObject(joe); 
    [...] 

當我將它傳遞parameters的:

int minconf, int maxconf, List<string> addresses 

0, 9999, ["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q", "mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"] 

生成的字符串s看起來像:

"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,"ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]}" 

而服務器要求應該像串:

"{"jsonrpc":"1.0","id":"1","method":"listunspent","params":[0,9999,["ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q","mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH"]]}" 

(注意周圍列表中的額外的支架)

我怎樣才能確保序列化對象是在我的期望格式?

回答

2

改變你foreach循環如下

 foreach (var p in parameters) 
     { 
      if (p.GetType().IsGenericType && p is IEnumerable) 
      { 
       JArray l = new JArray(); 
       foreach (var i in (IEnumerable)p) 
       { 
        l.Add(i); 
       } 
       props.Add(l); 
      } 
      else 
      { 
       props.Add(p); 
      } 
     } 
1

我認爲問題出在您想要添加到JArray中的列表地址參數中。

如果檢查JArray(道具)的大小,你會在添加地址之前看到,計數爲2,這是正確的,而插入地址後,就變成4

[ 0, 9999, 「ms8G6E6J4no1KgRt9j3KyoniRgazRgDX1Q」, 「mzPs8fwypX8oiRGHjYHXMSbSoEdz1zgcAH」 ]

你能包裹住地址爲複雜類型,並傳遞作爲參數?