以JSON格式查看SharePoint 2010列表

时间:2014-02-27 20:07:14

标签: json sharepoint sharepoint-2010

我准备使用Timeglider创建时间轴。一个要求是数据必须是JSON格式。对我来说,一个要求是需要客户端,因为我无法访问服务器或中央管理员。

当我尝试http://webname/_vti_bin/ListData.svc/listname时,我收到了访问权限的错误,但是当我发出http://webname/subsite/_vti_bin/ListData.svc/listname时,我没有拉数据的问题。

我的情况是列表在TLD上。我试着关注这篇文章How to retrieve a json object from a sharepoint list,但它与SP 2007有关。

2 个答案:

答案 0 :(得分:1)

要在SharePoint 2007,2010等中实现纯JSON支持,请查看此项目http://camelotjson.codeplex.com/。它要求将商业产品Camelot .NET Connector安装在服务器上。

如果您不喜欢商业广告,可以使用sp.js库,这是我写的一个小例子,尽情享受!

// Object to handle some list magic
var ListMagic = function () {
    /* Private variables */
    var that = this;
    var clientContext = SP.ClientContext.get_current();
    var web = clientContext.get_web();
    var lists = web.get_lists();

    /**
     * Method to iterate all lists
     */
    that.getLists = function () {

        clientContext.load(lists);
        clientContext.executeQueryAsync(execute, getFailed);

        function execute() {
            var listEnumerator = lists.getEnumerator();
            while (listEnumerator.moveNext()) {
                var l = listEnumerator.get_current();
                // TODO! Replace console.log with actual routine
                console.log(l.get_title());
            }
        }

        function getFailed() {
            // TODO! Implement fail management
            console.log('Failed.');
        }
    };


    /**
     * Method to iterate all fields of a list
     */
    that.getFields = function (listName) {

        // Load list by listName, if not stated try to load the current list
        var loadedList = typeof listName === 'undefined' ? lists.getById(SP.ListOperation.Selection.getSelectedList()) : that.lists.getByTitle(listName);
        var fieldCollection = loadedList.get_fields();

        clientContext.load(fieldCollection);
        clientContext.executeQueryAsync(execute, getFailed);

        function execute() {
            var fields = fieldCollection.getEnumerator();
            while (fields.moveNext()) {
                var oField = fields.get_current();

                // TODO! Replace console.log with actual routine
                var listInfo = 'Field Title: ' + oField.get_title() + ', Field Name: ' + oField.get_internalName();
                console.log(listInfo);
            }
        }

        function getFailed() {
            // TODO! Implement fail management
            console.log('Failed.');
        }
    };


    /**
     * Method to get a specific listitem
     */
    that.getListItem = function (itemId) {

        var loadedList = lists.getById(SP.ListOperation.Selection.getSelectedList());
        var spListItem = loadedList.getItemById(itemId);

        clientContext.load(spListItem);
        clientContext.executeQueryAsync(execute, getFailed);


        function execute() {
            // TODO! Replace console.log with actual routine
            //spListItem.get_fieldValues()
            console.log(spListItem.get_fieldValues()["Title"]);
        }

        function getFailed() {
            // TODO! Implement fail management
            console.log('Failed.');
        }
    };

    /**
     * Method to fake an init (optional)
     */
    that.init = function () {
        // Run any init functionality here
        // I.e
        that.getFields("Tasks");
    };

    return that;
};

// In case of no jquery use window.onload instead
$(document).ready(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        var sp = new ListMagic();
        sp.init();
    }, 'sp.js');
});

答案 1 :(得分:0)

就个人而言,我制作了HttpHandlers。我将它们安装在SharePoint isapi文件夹和GAC中,我可以像调用owssvr.dll一样调用它们。 http://servername/_vti_bin/myhttphandelr.dll  传递querystring变量或从jquery ajax调用它。您可以使用httpcontext并从中创建spcontext,并可以从SharePoint中的当前位置访问各种信息。然后你可以javascriptserialize对象并将它们作为JSON传递。寻找一些代码......坚持......我不能把所有的代码,但这应该让你接近。我使用它来向上下文菜单添加一个子菜单,允许用户删除或重命名文件,如果他们将文件上传到库并且版本为1.0并从库中收集文件并使用所选文件创建一个eml文件(s)作为附件。我们通常不会为用户提供删除权限。现在,您现在可以创建一个只包含SharePoint所需信息的类,并将其作为JSON传递。我对此唯一的挫折是,如果对dll进行任何更改,则需要iisreset。 无论如何,我每天晚上都会安排一个iisreset来保持它的新鲜感并且不受记忆臃肿的影响。我第二天来了,我的变化就在那里。很酷的是,spcontext包含有关SharePoint调用位置的当前位置的信息。所以,http://servername/_vti_bin/myhttphandelr.dll vs http://servername/subsite/library/_vti_bin/myhttphandelr.dll

我可以补充一下。不要尝试序列化SharePoint对象。一个是巨大而复杂的物体。二,我不认为它们标记为可序列化。只需创建自己的类,并使用SharePoint对象中所需的值填充它。

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using System.Web;
using System.Web.Script.Serialization;
using ADODB;
using interop.cdosys;
using Microsoft.SharePoint;


namespace owssvr2
{
    public class OWSsvr2 : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        private string cmd;
        ctx ctx = new ctx();
        private string currentuser;
        private SPContext SPcontext;
        private HttpContext cntx;
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            SPcontext = SPContext.GetContext(context); <-- Gets spcontext from the httpcontext
            cntx = context;
            ctx = GetData(context.Request); <-- I parse some information from the request to use in my app
            cmd = ctx.Cmd;
            ctx.User = context.User.Identity.Name;
            currentuser = context.User.Identity.Name;
            switch (cmd)
            {
                case "Delete":
                    Delete();
                    context.Response.Redirect(ctx.NextUsing);
                    break;
                case "HasRights":
                    HasRights();

                       JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string serEmployee = javaScriptSerializer.Serialize(ctx);
            context.Response.Write(serEmployee);
            context.Response.ContentType = "application/json; charset=utf-8";
                    break;
                case "Rename":
                    Rename(context);
                    //context.Response.Redirect(context.Request["NextUsing"]);
                    break;
                case "SendSingleFile":
                    try
                    {
                        context.Response.Clear();
                        context.Response.ClearHeaders();
                        context.Response.BufferOutput = true;
                        ADODB.Stream stream = SendSingleFile(context.Request["URL"]);
                        stream.Type = StreamTypeEnum.adTypeBinary;
                        stream.Position = 0;
                        context.Response.ContentType = "application/octet-stream";
                        context.Response.AddHeader("content-disposition", "attachment;filename=Email.eml");
                        IStream iStream = (IStream)stream;
                        byte[] byteArray = new byte[stream.Size];
                        IntPtr ptrCharsRead = IntPtr.Zero;
                        iStream.Read(byteArray, stream.Size, ptrCharsRead);
                        context.Response.BinaryWrite(byteArray);
                        context.Response.End();
                    }
                    catch(Exception ex) {context.Response.Write(ex.Message.ToString());  }
                    break;

                case "SendMultiFile":

                    try
                    {
                        //SendMultiFile(context.Request["IDs"]);
                        context.Response.Clear();
                        context.Response.ClearHeaders();
                        context.Response.BufferOutput = true;
                        ADODB.Stream stream = SendMultiFile(context.Request["IDs"]);
                        stream.Type = StreamTypeEnum.adTypeBinary;
                        stream.Position = 0;
                        context.Response.ContentType = "application/octet-stream";
                        context.Response.AddHeader("content-disposition", "attachment;filename=Email.eml");
                        IStream iStream = (IStream)stream;
                        byte[] byteArray = new byte[stream.Size];
                        IntPtr ptrCharsRead = IntPtr.Zero;
                        iStream.Read(byteArray, stream.Size, ptrCharsRead);
                        context.Response.BinaryWrite(byteArray);
                        context.Response.End();
                    }
                    catch(Exception ex) {context.Response.Write("There was an error getting the files. </br>"  + ex.Message.ToString());  }
                    break;
                case "FileInfo":
                     JavaScriptSerializer javaScriptSerializer1 = new JavaScriptSerializer();
                     string serEmployee1 = javaScriptSerializer1.Serialize(FileInfo(context));
                     context.Response.Write(serEmployee1);
            context.Response.ContentType = "application/json; charset=utf-8";

                    break;
                case "UsersInGroups":
                  UsersInGroups ug = new  UsersInGroups(context, context.Request["job"],context.Request["groups"]);
                    break;
            }


        }