将OData转换为对象

问题描述 投票:1回答:2

我正在调用Microsoft Graph来获取用户的经理:

/v1.0/name.onmicrosoft.com/users/[email]/manager

我正在尝试反序列化对用户的响应。响应看起来像这样。

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
    "@odata.type": "#microsoft.graph.user",
    "id": "xxxxxxxxxxxxxxxxx",
    "businessPhones": ["+46 xxx xxx xxx"],
    "displayName": "Susanne xxx",
    "givenName": "Susanne",
    "jobTitle": "sales",
    "mail": "[email protected]",
    "mobilePhone": "+46 xxx xxxx",
    "officeLocation": null,
    "preferredLanguage": null,
    "surname": "Dannstedt",
    "userPrincipalName": "[email protected]"
}

我尝试像这样序列化它:

var hasValue = jObject.TryGetValue("userPrincipalName", StringComparison.InvariantCultureIgnoreCase, out var value);
if (hasValue)
{
    return value.ToObject<User>();
}

userPrincipalName具有值,但转换失败。我假设这是因为User类没有@odata.context@odata.type

什么是正确的转换方式?

asp.net-core azure-active-directory microsoft-graph
2个回答
1
投票

不。您正在尝试将字符串转换为用户。

假设你有JSON,你可以进行如下转换:

string json = ...;
var user = JsonConvert.DeserializeObject<User>(json);

假设User类如:

public class User
{
    public string UserPrincipalName { get; set; }
    //Implement other properties
}

0
投票

userPrincipalName具有值,但转换失败。我假设是因为User类没有@ odata.context和@ odata.type?

虽然juunas提供了答案,但我发现以下代码可以按预期工作。我只是在没有使用任何帐户登录的情况下跟踪Microsoft Graph Explorer请求,并模拟我的配置文件REST API,如下所示:

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "{token:https://graph.microsoft.com/}");
var result = await client.GetAsync("https://proxy.apisandbox.msdn.microsoft.com/svc?url=https%3A%2F%2Fgraph.microsoft.com%2Fv1.0%2Fme%2F");

var jsonString = await result.Content.ReadAsStringAsync();
var jObject = JObject.Parse(jsonString);
var user = jObject.ToObject<User>();

自定义用户类:

public class User
{
    public string UserPrincipalName { get; set; }
    public string displayName { get; set; }
    public string givenName { get; set; }
    //TODO:
}

对于您的场景,我假设您需要检查您的User模型,您也可以按照Microsoft Graph提供的Microsoft.Graph.User模型,因为Marc LaFleur评论说要缩小此问题。此外,您可以提供详细的错误消息,以便我们解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.