在sharepoint 2010 webpart中解析json

时间:2012-08-23 12:05:09

标签: javascript ajax json sharepoint-2010 asp.net-ajax

所以我在php中做了

$.ajax({
         url: 'parser.php',
         type: 'POST',
         data: 'Data=' + $.toJSON(schedule),
         success: function (res) {
                  alert(res);
         }
       });

计划的对象

stdClass object {
   weeks => array (1) (
     [0] => stdClass object {
       0 => stdClass object {}
       1 => stdClass object {}
       2 => stdClass object {}
       3 => stdClass object {}
       4 => stdClass object {}
       5 => stdClass object {}
       6 => stdClass object {}
       alltime => (int) 60
     }
   )
   alltime => (int) 60
   hours => (int) 60
}

如何将ajax请求传递给sharepoint 2010? 然后在服务器上解析。谢谢。

1 个答案:

答案 0 :(得分:6)

使用.NET 4.0非常容易。来自The Rise Of JSON

WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString(
    "https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);

不幸的是,SharePoint 2010构建于.NET 3.5之上,因此我们无法使用该代码。

相反,要调用Web服务,我们可以使用C#中的Getting data from a REST service中描述的代码:

public string GetMessage( string endPoint )
{
    HttpWebRequest request = CreateWebRequest( endPoint );

    using ( var response = (HttpWebResponse) request.GetResponse( ) )
    {
        var responseValue = string.Empty;

        if ( response.StatusCode != HttpStatusCode.OK )
        {
            string message = String.Format( "POST failed. Received HTTP {0}", 
                response.StatusCode );
            throw new ApplicationException( message );
        }

        // grab the response
        using ( var responseStream = response.GetResponseStream() )
        {
            using ( var reader = new StreamReader( responseStream ) )
            {
                responseValue = reader.ReadToEnd();
            }
        }

        return responseValue;
    }
}

然后我们可以使用JavaScriptSerializer来解析JSON响应。

var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(response);

JavaScriptSerializer有点古怪。如果你想要一些更优雅的东西,你可以使用像Json.NET这样的第三方库来解析JSON响应。

JObject o = JObject.Parse(responseValue);

我希望这有帮助,