我正在尝试解析SharePoint列表中的JSON响应,并将某些节点解析为列表。可以有多个记录。我正在使用Newsoft Json反序列化响应。一切正常,我创建的foreach循环一次遍历结果。同样在foreach循环中,items变量将数据作为结果变量。
以下是代码:
static List<string> get_json_unsubscribe()
{
int counter = 0;
List<string> list_of_json_users = new List<string>();
String url = "http://server/site/_api/lists/getbytitle('listname')"
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(url);
endpointRequest.Credentials = CredentialCache.DefaultCredentials;
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
Stream receiveStream = endpointResponse.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
dynamic results = JsonConvert.DeserializeObject<dynamic>(readStream.ReadToEnd());
foreach (var item in results)
{
string userid= results.d.results[counter].userid
list_of_json_users.Add(userid);
counter++;
}
return list_of_json_users;
}
答案 0 :(得分:1)
终点:
http://server/site/_api/lists/getbytitle('<listtitle>')
返回 List
资源属性,您可能需要此端点:
http://server/site/_api/lists/getbytitle('<listtitle>')/items
返回列表数据(ListItemCollection
资源)
要反序列化您的JSON,您可以引入一个模型:
public class UserInfo
{
[JsonProperty("AuthorId")]
public string AuthorId { get; set; }
}
public class UserInfoResult
{
[JsonProperty("results")]
public List<UserInfo> UserInfoCollection { get; set; }
}
public class UserInfoResultRoot
{
[JsonProperty("d")]
public UserInfoResult Result { get; set; }
}
注意:在
AuthorId
提供的示例ListItem
属性中 资源被标记为反序列化
在这种情况下反序列化列表项:
dynamic results = JsonConvert.DeserializeObject<dynamic>(readStream.ReadToEnd());
foreach (var item in results)
{
string userid= results.d.results[counter].userid
list_of_json_users.Add(userid);
counter++;
}
可以替换为:
var json = readStream.ReadToEnd();
var data = JsonConvert.DeserializeObject<UserInfoResultRoot>(json);
list_of_json_users
可以像这样初始化:
list_of_json_users = data.Result.UserInfoCollection.Select(ui => ui.AuthorId).ToList();