我想从url中获取json的特定对象数据,下面的代码给了我。我需要第二个对象' EmailAddressSuffices'
WebRequest request = WebRequest.Create(
"https://atea-dev.accesscontrol.windows.net/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&reply_to=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&context=&request_id=&version=1.0&callback=");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
答案 0 :(得分:0)
使用JSON.Net,您可以轻松地反序列化JSON响应:
解决方案1
1。创建一个类来将JSON映射到:
public class ResponseObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("LoginUrl")]
public string LoginUrl { get; set; }
[JsonProperty("LogoutUrl")]
public string LogoutUrl { get; set; }
[JsonProperty("ImageUrl")]
public string ImageUrl { get; set; }
[JsonProperty("EmailAddressSuffixes")]
public IList<string> EmailAddressSuffixes { get; set; }
}
2。使用JsonConvert.Deserialize<ResponseObject>()
var myresponse = JsonConvert.DeserializeObject<List<ResponseObject>>(responseFromServer);
string email = myresponse[1].EmailAddressSuffixes[0];
解决方案2
如果您不想打扰整个事物,那么您可以这样做:
JArray array = JArray.Parse(responseFromServer);
string q = array[1]["EmailAddressSuffixes"][0].ToString();
但是你应该确保你的对象具有正确的格式(以及数组中正确数量的项目。