我需要帮助,我需要从下面的json对象获取UserID和UserID的值
{"data":{"UserID":"MS100000041","RoleID":5}}
这是我的代码:
public class UserDetails
{
public string UserID { get; set; }
public int RoleID { get; set; }
}
public async Task Login(string url)
{
try
{
var uri = new Uri(url);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var Item = JsonConvert.DeserializeObject<UserDetails>(content);
string userid = Item.UserID;
int roleid= Item.RoleID;
}
else
{
Application.Current.Properties["response"] = response;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
但是这个值userid和roleid显示为null。请问我如何获得这些价值
答案 0 :(得分:2)
根据所提供的JSON,您必须访问UserID
和RoleID
,例如Item.data.UserID
和Item.data.RoleID
答案 1 :(得分:2)
正如hellowstone所指出的那样
[TestClass]
public class Test2
{
[TestMethod]
public void Test()
{
var item = JsonConvert
.DeserializeObject<Payload>("{\"data\":{\"UserID\":\"MS100000041\",\"RoleID\":5}}")
.data;
Assert.AreEqual(item.RoleID, 5);
Assert.AreEqual(item.UserID, "MS100000041");
}
class Payload
{
public UserDetails data { get; set; }
}
class UserDetails
{
public int RoleID { get; set; }
public string UserID { get; set; }
}
}
答案 2 :(得分:2)
扩展hellowstone的答案:
void Main()
{
var content = @"{""data"":{""UserID"":""MS100000041"",""RoleID"":5}}";
var Item = JsonConvert.DeserializeObject<UserDetails>(content);
Console.WriteLine(Item.data.UserID);
Console.WriteLine(Item.data.RoleID);
}
public class UserDetails
{
public class Data
{
public string UserID { get; set; }
public int RoleID { get; set; }
}
public Data data { get; set; }
}
输出是:
MS100000041
5
答案 3 :(得分:0)
using Newtonsoft.Json;
public async Task Login(string url)
{
List<UserDetails> ud = new List<UserDetails> ();
try
{
var uri = new Uri(url);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
JObject results = JObject.Parse (content);
var results2 = results ["data"];
foreach (var i in results2) {
ud.Add (new UserDetails () {
UserID = i["UserID"].ToString();
RoleID = int.Parse(i["RoleID"].ToString());
});
}
}
else
{
Application.Current.Properties["response"] = response;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}