2015-10-15 23 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

这正是我想要的。非常感谢你的帮助。 –