2013-03-16 60 views
0

我使用NewtonSoft.Json解析器解析远程URL。验证远程JSON比解析它

我的遥控JSON例子如下

Kerberos.load({"todays" : "Fri, Mar 15", 
    "datas" : [ 
      { 
       "id" : "2021200303" 
      } 
      ]}); 

我解析JSON例子如下

using (var WebClient = new System.Net.WebClient()) 
{ 
    WebClient.Encoding = System.Text.Encoding.UTF8; 

    var _Json = WebClient.DownloadString(_MyJsonRemoteURL_); 

    _Json = _Json.Replace("Kerberos.load(", ""); 
    _Json = _Json.Replace("]});", "]}"); 

    dynamic _Dynamic = JsonConvert.DeserializeObject(_Json); 
    foreach (var _JsonNode in _Dynamic.datas) 
    { 
     MessageBox.Show(_JsonNode.SelectToken("id").ToString()); 
    } 
} 

那么,有没有什么办法来验证远程JSON字符串,而无需使用更换方法?

+1

除了这不是有效的JSON,它是JSONP。 – svick 2013-03-16 02:23:26

+0

@svick谢谢。窦你有任何建议解析JSONP – Kerberos 2013-03-16 02:25:31

回答

-2

这是非常可能的,如果你想这样做的JSON,请Contract testing a json service in .net

交叉张贴在这里的代码为快速参考,更详细的结帐链接

[Test] 
public void ShouldBeAbleToValidateTheJSONServiceResponseForFunctionalityA() 
{ 
    const string schemaJson = @" 
{ 
    'description': 'Service Response', 
    'type': 'object', 
    'properties': { 
     'product': { 
      'type': 'object', 
      'properties': { 
       'availability': { 
         'type': 'array', 
         'items': { 
            'type': 'object', 
            'properties': { 
                'Local': { 'type' : 'number'}, 
                'Storehouse': { 'type' : 'number'}, 
               } 
           } 
        } 
      }   
     } 
    } 
}"; 
    var parameters = new Dictionary<string, object> { { "id", 1 }, { "city", "Chennai" } }; 
    AssertResponseIsValidSchema(schemaJson, parameters); 
} 
+0

这似乎没有任何关系的问题:解析JSONP。 – svick 2013-03-16 17:11:01

+0

@svick是的,我同意起初我以为它仅适用于JSON回答后,我意识到,它JSONP – 2013-03-16 17:24:46

+0

@svick更新了答案以及表明其对JSON – 2013-03-16 17:26:41