Запрос GET Microsoft Graph Api не может десериализовать объект JSON при вызове приложенийC#

Место общения программистов C#
Ответить
Anonymous
 Запрос GET Microsoft Graph Api не может десериализовать объект JSON при вызове приложений

Сообщение Anonymous »

Я делаю вызов GET-запроса, чтобы вернуть все приложения с их идентификаторами и датой истечения срока действия пароля. Я работал с Graph Explore, который предлагает Microsoft, и мне это очень помогло. Код, который у меня есть, возвращает HTTP-запрос, а затем при попытке десериализации он терпит неудачу с приведенной ниже ошибкой. Я потратил много времени на SOF, просматривая аналогичный пост, но, похоже, ничего не работает. Я чувствую, что, возможно, здесь что-то упущено или я делаю это неправильно.
Я также застрял на более старой версии Graph Nugget pkg v4.41.0, а Core находится на v2. .0.13. Я пошел их обновить, и в приложении было много критических изменений, и у меня пока нет времени все переписывать.
Я получаю следующую ошибку:

Код: Выделить всё

"Message": "An error has occurred.",
"ExceptionMessage": "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[Microsoft.Graph.Application]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath '['@odata.context']', line 1, position 18.",
"ExceptionType": "Newtonsoft.Json.JsonSerializationException",
"StackTrace": "   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)\r\n   at Newtonsoft.Json.Serialization...

Код: Выделить всё

        public async Task GetAppExpList()
{
List apps = null;

// query string for url call
var url = this.GetGraphUrl($"{Consts.GraphUrl}?$select=id,passwordCredentials&$format=json");

// tried to do this with the built in Graph methods
List options = new List
{
new QueryOption("$select", "id,DisplayName,passwordCredentials"),
new QueryOption("$format", "json")
};

// Here I wanted to see what was brought back. No PasswordCreds for some reason
var test = await _graphClient.Applications.Request(options).GetAsync();

// GET request to the Applications Graph Api
var response = await this.HttpHandler.SendGraphGetRequest(url);

// Returns JSON data
if (response.IsSuccessStatusCode)
{
// Shows the correct data in JSON Format
var rawData = await response.Content.ReadAsStringAsync();

// Throws error above.
apps = JsonConvert.DeserializeObject(rawData);

}

return apps;
}
Вот JSON, который возвращается для var rawData = await response.Content.ReadAsStringAsync();

Код: Выделить всё

{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#applications(id,passwordCredentials)"
,"value":[
{
"id":"00000000-0000-0000-0000-000000000000",
"displayName":"App 1 name Here",
"passwordCredentials":[]
},
{
"id":"00000000-0000-0000-0000-000000000001",
"displayName":" App 2 name here",
"passwordCredentials":[]
},
{
"id":"00000000-0000-0000-0000-000000000002",
"displayName":"App 3 name here",
"passwordCredentials":[
{
"customKeyIdentifier":null,
"displayName":"secret",
"endDateTime":"2025-01-30T14:46:40.985Z",
"hint":"oHI",
"keyId":"00000000-0000-0000-0000-0000000000",
"secretText":null,
"startDateTime":"2023-01-31T14:46:40.985Z"
}
]
}
]
}

Подробнее здесь: https://stackoverflow.com/questions/782 ... ing-applic
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»