2015-10-15 75 views
1

我正在使用Web服務來獲取響應,並發現Json格式不正確。請參閱下面的示例。如何在C#中使用JsonConvert處理不良的Json響應

的Object結構是:

public class Action 
      { 
       public string serialNumber { get; set; } 
       public string method1 { get; set; } 
       public string recipient1 { get; set; } 
       public string notifyon1 { get; set; } 
      } 

我們具有其具有值 「1 @ test.com,2 @ test.com,3 @ test.com」 的字段 「收信地址」,則API響應的json如下。

壞JSON響應:

{"serialNumber": "2471", 
"method1": "email", 
"recipient1": "[email protected]", 
"[email protected]": "", 
"[email protected]": "", 
"notifyon1": "warning", 
    "critical": ""} 

這應該是:

{"serialNumber": "2471", 
"method1": "email", 
"recipient1": "[email protected],[email protected],[email protected]", 
"notifyon1": "warning,critical"} 

首先,我試圖用正則表達式來這些電子郵件值轉換爲右場。但後來我發現它發生了包括逗號「,」在內的所有價值。如上述示例中的「Notifyon1」。

現在我想如果有任何方法可以解析JSON,當它找到「[email protected]」時,然後檢查對象,如果它不是一個屬性,然後將它作爲一個值放入前一個字段「收信地址」。

感謝您的幫助。

回答

0

無論屬性中的空值如何,這都可以工作。

using Newtonsoft.Json; 

private Action HandleBadJson(string badJson) 
{ 
    Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(badJson); 
    Action act = new Action(); 
    List<string> propertyNames = act.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Select(p => p.Name).ToList(); 
    string currentProperty = ""; 
    foreach (var keyValPair in dictionary) 
    { 
     if (propertyNames.Contains(keyValPair.Key)) 
     { 
      currentProperty = keyValPair.Key; 
      act.GetType().GetProperty(currentProperty).SetValue(act, keyValPair.Value); 
      continue; 
     } 
     else 
     { 
      var currentValue = act.GetType().GetProperty(currentProperty).GetValue(act, null); 
      string value = currentValue + "," + keyValPair.Key; 
      value = value.Trim(','); 
      act.GetType().GetProperty(currentProperty).SetValue(act, value); 
     } 
    } 
    return act; 
} 
+0

謝謝Jhmt。你的功能看起來不錯。我會測試它。如果有空值,有什麼想法嗎?似乎我可以使用keyvalpair.key來與對象的屬性進行比較。 –

+0

@AndyShao如果有空值,我已經更新了我的代碼來處理壞json。 – jhmt

+0

這正是我想要的。非常感謝你的幫助。 –