본문 바로가기
개발언어/SharePoint

Sharepoint ListItemCollect to JSON webservice return

by 엔돌슨 2014. 12. 16.
반응형


참고할만한 사이트가 있다.


http://geekswithblogs.net/DougLampe/archive/2012/04/20/two-best-sharepoint-utility-methods-ever-written.aspx


간단히 만들어 보았다.

C#에서 DataTable로 만들고 다시 Json string 으로 웹서비스가 리턴하는 것이다.



/// <summary> /// 데이타를 가져온다. /// </summary> /// <returns></returns> public DataTable GetListAsDataTable() {

DataTable dt=new DataTable();

try {

Web web=m_con.Site.RootWeb;

CamlQuery camlQuery=new CamlQuery();

camlQuery.ViewXml="<View Scope=\"RecursiveAll\">" //하위폴더 탐색 //"<View>" //+"<QueryOptions><ViewAttributes Scope='Recursive' /></QueryOptions>" +"<RowLimit>4</RowLimit>" +"<Query>" +"<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>" +"<Where>" +"<Eq><FieldRef Name='FolderLocation' /><Value Type='Text'>필터2</Value></Eq>" +"<And>" +"<Eq><FieldRef Name='FolderLocation' /><Value Type='Text'>필터1</Value></Eq>" +"<And>" +"<Eq><FieldRef Name='FSObjType' /><Value Type='int'>0</Value></Eq>" +"<Eq><FieldRef Name='FolderLocation' /><Value Type='Text'>필터3</Value></Eq>" +"</And>" +"</And>" +"</And>" +"</Where>" +"</Query>" +"</View>";

//공지사항 상위폴더 camlQuery.FolderServerRelativeUrl="/sites/Boards/Lists/Boards";

List list=web.Lists.GetById(new Guid(m_noticeList.GUID));

ListItemCollection listitemCollection=list.GetItems(camlQuery);

FieldCollection fields=list.Fields;

m_con.Load(fields);

m_con.Load(listitemCollection);

m_con.ExecuteQuery();

// Columns Add foreach (Field field in fields) {

if (!dt.Columns.Contains(field.Title)) {

dt.Columns.Add(field.Title, typeof(object));

string temp=field.InternalName;

}

}

// Convert : listitemCollection to DataTable foreach (ListItem item in listitemCollection) {

DataRow row=dt.NewRow();

dt.Rows.Add(row);

foreach (Field field in fields) {

string key=field.Title;

if (item.FieldValues.ContainsKey(field.InternalName)) {

if (item[field.InternalName]==null) {

row[key]=DBNull.Value;

}

else {

row[key]=item[field.InternalName];

}

}

}

}

return dt;

}

catch (Exception e) {

m_msg=e.Message;

}

return dt;

}

/// <summary> /// DataTable To JSON /// </summary> /// <returns></returns> public string GetListAsJsonp() {

DataTable dt=GetListAsDataTable();

if (dt==null || dt.Rows.Count==0) {

return string.Empty;

}

JavaScriptSerializer serializer=new JavaScriptSerializer();

List<object> rowData=new List<object>();

foreach (DataRow row in dt.Rows) {

rowData.Add(row.ItemArray);

}

var data=new {

fields=dt.Columns.Cast <DataColumn>().Select(x=> x.ColumnName).ToArray(), rowData=rowData.ToArray()

}

;

return serializer.Serialize(data);

}