JsonException при десериализации определенного классаC#

Место общения программистов C#
Ответить
Anonymous
 JsonException при десериализации определенного класса

Сообщение Anonymous »

Я получаю исключение JsonException в своем клиенте, когда он пытается десериализовать строку. Поигравшись с API, я определил, что произошел сбой в конкретном разделе, поскольку другие его части десериализовались правильно и не выдают ошибку.
В API существует класс, который содержит как минимум два идентификатора других классов и потенциальный третий идентификатор другого класса, а также свой собственный идентификатор. Он также содержит некоторые атрибуты, которые будут использоваться на стороне клиента.
Я получаю следующую ошибку:

JsonException: значение JSON не удалось преобразовать в UILibrary.Api.AppRoleId. Путь: $.appPermissionsSaved[0].appRoleId | НомерЛинии: 0 | BytePositionInLine: 25761.
System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
ApiException: не удалось десериализовать поток тела ответа как UILibrary .Api.UserInformationRequestResponse.
JsonException: значение JSON не удалось преобразовать в UILibrary.Api.AppRoleId. Путь: $.appPermissionsSaved[0].appRoleId | НомерЛинии: 0 | BytePositionInLine: 25761.
UILibrary.Api.UserinfoClient.ReadObjectResponseAsync(ответ HttpResponseMessage, заголовки IReadOnlyDictionary, CancellationToken cancelToken) в ApiClient.cs

+

var typedBody = ожидание System.Text.Json.JsonSerializer.DeserializeAsync(responseStream, JsonSerializerSettings, cancelToken).ConfigureAwait(false);

Я предоставляю пример JSON, который предоставляет конечная точка API и что поступает из схемы OpenAPI.
Схема (ненужные разделы удалены для краткости, и да) оно все еще длинное):

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

{
"openapi": "3.0.1",
"info": {
"version": "1.0"
},
"paths": {
"/api/Userinfo": {
"get": {
"tags": [
"Userinfo"
],
"summary": "Retrieves information about the user from the database",
"operationId": "Userinfo",
"responses": {
"401": {
"description": "If the user did not login correctly",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"200": {
"description": "Returns the claims, permissions, roles, and permissions saved",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserInformationRequestResponse"
}
}
}
}
}
}
},
"/api/UserinfoVerify": {
"get": {
"tags": [
"UserinfoVerify"
],
"summary": "Retrieves information about the user from the database",
"operationId": "UserinfoVerify",
"responses": {
"401": {
"description": "If the user did not login correctly",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"200": {
"description": "Returns the claims, permissions, roles, and permissions saved",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserInformationRequestResponse"
}
}
}
}
}
}
},
//Removed
},
"components": {
"schemas": {
"AppPermission": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/GuidAggregateRootId"
},
"created": {
"type": "string",
"format": "date-time"
},
"createdBy": {
"type": "string",
"nullable": true
},
"lastModified": {
"type": "string",
"format": "date-time",
"nullable": true
},
"lastModifiedBy": {
"type": "string",
"nullable": true
},
"uniqueName": {
"type": "string",
"nullable": true,
"readOnly": true
},
"nodes": {
"$ref": "#/components/schemas/NodeValues"
},
"nodeType": {
"type":  "string",
"nullable": true,
"readOnly": true
},
"permissionName": {
"type": "string",
"nullable": true,
"readOnly": true
},
"description": {
"type": "string",
"nullable": true,
"readOnly": true
},
"itemType": {
"type": "string",
"nullable": true,
"readOnly": true
},
"application": {
"type": "boolean",
"readOnly": true
}
},
"additionalProperties": false
},
"AppPermissionId": {
"type": "object",
"properties": {
"value": {
"type": "string",
"format": "uuid"
}
},
"additionalProperties": false
},
"AppPermissionSavedId": {
"type": "object",
"properties": {
"value": {
"type": "integer",
"format": "int32"
}
},
"additionalProperties": false
},
"AppPermissionsSaved": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/AppPermissionSavedId"
},
"appRoleId": {
"$ref": "#/components/schemas/AppRoleId"
},
"appPermissionId": {
"$ref": "#/components/schemas/AppPermissionId"
},
"settingValue": {
"type": "string",
"nullable": true,
"readOnly": true
},
"attribute": {
"type": "string",
"nullable": true,
"readOnly": true
},
"application": {
"type": "boolean",
"readOnly": true
},
"itemName": {
"type": "string",
"nullable": true,
"readOnly": true
},
"applicationId": {
"$ref": "#/components/schemas/ClientApplicationId"
}
},
"additionalProperties": false
},
"AppRole": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/GuidAggregateRootId"
},
"roleName": {
"type": "string",
"nullable": true,
"readOnly": true
},
"active": {
"type": "boolean",
"readOnly": true
},
"concurrencyStamp": {
"type": "string",
"nullable": true,
"readOnly": true
},
"permissions": {
"type": "array",
"items": {
"$ref": "#/components/schemas/AppPermissionsSaved"
},
"nullable": true,
"readOnly": true
}
},
"additionalProperties": false
},
"AppRoleId": {
"type": "object",
"properties": {
"value": {
"type": "string",
"format": "uuid"
}
},
"additionalProperties": false
},
"Claim": {
"type":  "object",
"properties": {
"issuer": {
"type": "string",
"nullable": true,
"readOnly": true
},
"originalIssuer": {
"type": "string",
"nullable": true,
"readOnly": true
},
"properties": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"nullable": true,
"readOnly": true
},
"subject": {
"$ref": "#/components/schemas/ClaimsIdentity"
},
"type": {
"type": "string",
"nullable": true,
"readOnly": true
},
"value": {
"type": "string",
"nullable": true,
"readOnly": true
},
"valueType": {
"type": "string",
"nullable": true,
"readOnly": true
}
},
"additionalProperties": false
},
"ClientApplication": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/GuidAggregateRootId"
},
"domainEvents": {
"type": "array",
"items": {
"$ref": "#/components/schemas/IDomainEvent"
},
"nullable": true,
"readOnly": true
},
"clientID": {
"type": "string",
"nullable": true,
"readOnly": true
},
"clientSecret": {
"type": "string",
"nullable": true,
"readOnly": true
},
"consentType": {
"type": "string",
"nullable": true,
"readOnly": true
},
"displayName": {
"type": "string",
"nullable": true,
"readOnly": true
},
"displayNames": {
"uniqueItems": true,
"type": "array",
"items": {
"type": "string"
},
"nullable": true,
"readOnly": true
},
"postLogoutRedirectUris": {
"uniqueItems": true,
"type": "array",
"items": {
"type": "string",
"format": "uri"
},
"nullable": true,
"readOnly": true
},
"redirectUris": {
"uniqueItems": true,
"type": "array",
"items": {
"type": "string",
"format": "uri"
},
"nullable": true,
"readOnly": true
},
"permissions": {
"uniqueItems": true,
"type": "array",
"items": {
"type": "string"
},
"nullable": true,
"readOnly": true
},
"requirements": {
"uniqueItems": true,
"type": "array",
"items": {
"type": "string"
},
"nullable": true,
"readOnly":  true
},
"clientType": {
"type": "string",
"nullable": true,
"readOnly": true
},
"applicationType": {
"type": "string",
"nullable": true,
"readOnly": true
},
"jsonWebKeySet": {
"$ref": "#/components/schemas/JsonWebKeySet"
},
"settings": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"nullable": true,
"readOnly": true
}
},
"additionalProperties": false
},
"ClientApplicationId": {
"type": "object",
"properties": {
"value": {
"type": "string",
"format": "uuid"
}
},
"additionalProperties": false
},
"GuidAggregateRootId": {
"type": "object",
"properties": {
"value": {
"type": "string",
"format": "uuid"
}
},
"additionalProperties": false
},
"Int32AggregateRootId": {
"type": "object",
"properties": {
"value": {
"type": "integer",
"format": "int32"
}
},
"additionalProperties": false
},
"NodeValues": {
"type": "object",
"properties": {
"nodeOne": {
"type": "string",
"nullable": true
},
"nodeTwo": {
"type": "string",
"nullable": true
},
"nodeThree": {
"type": "string",
"nullable": true
},
"nodeFour": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false
},
"UserInformationRequestResponse": {
"type": "object",
"properties": {
"claims": {
"type": "object",
"additionalProperties": {},
"nullable": true
},
"appRoles": {
"uniqueItems": true,
"type": "array",
"items": {
"$ref": "#/components/schemas/AppRole"
},
"nullable": true
},
"appPermissions": {
"uniqueItems": true,
"type": "array",
"items": {
"$ref": "#/components/schemas/AppPermission"
},
"nullable": true
},
"appPermissionsSaved": {
"type": "array",
"items": {
"$ref": "#/components/schemas/AppPermissionsSaved"
},
"nullable": true
},
"errorDescription": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false
}
},
"securitySchemes": {
}
},
"security": [
{
"Bearer": []
}
]
}
Строка Json:

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

{
"claims": {
"sub": "d5b321da-6b4d-4e06-9feb-81e898119ccc",
"email":  "test@test.com",
"email_verified": true,
"role": [
{
"roleName": "Secure",
"active": true,
"id": {
"value": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c"
}
}
]
},
"appRoles": [
{
"roleName": "Secure",
"active": true,
"concurrencyStamp": "174351b9-dd3b-4eb1-a5f0-8d7887b7cff4",
"permissions": [],
"id": {
"value": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c"
}
}
],
"appPermissions": [
{
"uniqueName": "Navigation_Roles_ViewRolesManagement",
"nodes": {
"nodeOne": "Navigation",
"nodeTwo": "Roles",
"nodeThree": "",
"nodeFour": ""
},
"nodeType": "-ClientApplication-",
"permissionName": "View Roles Management",
"description": "Allows an Authorized User to access Role Management functions",
"itemType": "Client, IsAuthorized",
"application": true,
"id": {
"value": "ae51ab14-4521-4b91-95b8-07d8e626b67b"
},
"created": "0001-01-01T00:00:00",
"createdBy": null,
"lastModified": null,
"lastModifiedBy": null,
"domainEvents": [
{}
]
},
{
"uniqueName": "Edit_User_Applications",
"nodes": {
"nodeOne": "Edit",
"nodeTwo": "User",
"nodeThree": "Applications",
"nodeFour": ""
},
"nodeType": "-ClientApplication-",
"permissionName": "Update User Databases By Id",
"description": "Allows user to update the list of applications for a specific user",
"itemType": "Client, Api",
"application": true,
"id": {
"value": "3392d517-1265-498a-b441-0817d2a28994"
},
"created": "0001-01-01T00:00:00",
"createdBy": null,
"lastModified": null,
"lastModifiedBy": null,
"domainEvents": [
{}
]
},
{
"uniqueName": "Manage_Permissions",
"nodes": {
"nodeOne": "Manage",
"nodeTwo": "Permissions",
"nodeThree": "",
"nodeFour": ""
},
"nodeType": "-Main-",
"permissionName": "Permissions Management",
"description": "Allows users the ability to access the Permissions Controller",
"itemType": "Api",
"application": false,
"id": {
"value": "a24d6e4e-6824-49ac-9bf3-e00193953ad5"
},
"created": "0001-01-01T00:00:00",
"createdBy": null,
"lastModified": null,
"lastModifiedBy": null,
"domainEvents": [
{}
]
},
{
"uniqueName": "Manage_Users",
"nodes": {
"nodeOne": "Manage",
"nodeTwo": "Users",
"nodeThree":  "",
"nodeFour": ""
},
"nodeType": "-Main-",
"permissionName": "User Management",
"description": "Allows users the ability to access the Users Controller",
"itemType": "Api",
"application": false,
"id": {
"value": "5769a54e-7e92-4ea4-ace3-f9f60901e865"
},
"created": "0001-01-01T00:00:00",
"createdBy": null,
"lastModified": null,
"lastModifiedBy": null,
"domainEvents": [
{}
]
}
],
"appPermissionsSaved": [
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "ae51ab14-4521-4b91-95b8-07d8e626b67b",
"settingValue": "true",
"attribute": "IsApproved, IsAuthorized",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 1,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "3392d517-1265-498a-b441-0817d2a28994",
"settingValue": "true",
"attribute": null,
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 2,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "d3b32e20-ab88-4da3-bea0-0a9fae3045dc",
"settingValue": "true",
"attribute": null,
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 3,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "036d8095-4c2d-4273-8466-15dd84b66b48",
"settingValue": "true",
"attribute": null,
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 4,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "49da4b4b-a2ff-463d-86ed-346363d6f9ef",
"settingValue": "true",
"attribute": "IsApproved, IsAuthorized, IsDomainTypeUser",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 14,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "3feeeafd-56af-4781-9d86-3553a583ff9c",
"settingValue": "true",
"attribute": "IsApproved, IsAuthorized",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 15,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "f0715bc3-95b0-4fbc-898e-68cedd0ff839",
"settingValue":  "true",
"attribute": "IsApproved, IsAuthorized",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 22,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "a11722c4-3853-4635-9dae-69329a1a7698",
"settingValue": "true",
"attribute": "IsApproved, IsAuthorized",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 23,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "02984b5a-84c5-4b1c-86f4-71f1fa5e816b",
"settingValue": "true",
"attribute": "IsAuthenticated",
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 24,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "e36703d2-7c6c-42ff-8d80-fe0627a1ed63",
"settingValue": "true",
"attribute": null,
"application": true,
"itemName": "app-man",
"applicationId": "1d4603a9-19b1-440a-9c03-7488629c96bd",
"id": 43,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "b031eb0c-554c-45d4-8cf2-6b0eec1fac04",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 1,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "bed2ee5b-9b6f-4e99-a69e-7abff10112fa",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 2,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "355d769e-9407-4de1-b54f-82221b60ab7e",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 3,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "620e2537-2d58-4c59-aaaf-9c5cec8815aa",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 4,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "24e30568-badd-440f-b121-b4170efab9d1",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id":  5,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "ef8e7d75-8898-4740-b9bd-c843e78aae23",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 6,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "088883ca-3c72-47e6-9d18-d802931e3b3f",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 7,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "28e93707-e48d-4a74-9a69-d8eb46601856",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 8,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "a24d6e4e-6824-49ac-9bf3-e00193953ad5",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 9,
"domainEvents": []
},
{
"appRoleId": "37c0348a-df35-4a8b-b9b9-7ba7d369ba6c",
"appPermissionId": "5769a54e-7e92-4ea4-ace3-f9f60901e865",
"settingValue": "true",
"attribute": null,
"application": false,
"itemName": null,
"applicationId": null,
"id": 10,
"domainEvents": []
}
],
"errorDescription": null
}
Я знаю, что существует вероятность того, что из-за сбоя в первом случае он может также потерпеть неудачу и для любого из двух других потенциальных идентификаторов. Я ищу способ исправить текущую проблему и предотвратить потенциальное возникновение других проблем.
Одна из вещей, которые я пробовал, — это вместо использования AppPermissionsSaved для списка я сделал список объектов. В данном случае это не сработало, но мне не удалось преобразовать объект обратно в AppPermissionsSaved в клиенте. Это либо не удалось, как указано выше, когда я выполнил JsonSerializer.Deserialize(jsonString);, либо каким-то образом полностью пропустил это.
Как уже говорилось ранее, я удалил AppPermissionsSaved при устранении неполадок и не обнаружил ошибки десериализатора после соответствующего обновления схемы OpenApi и наличия только утверждений, Approle, AppPermissions и errorDescription. Это сработало отлично и позволило мне продолжить. Хотя в AppPermissionsSaved есть необходимая информация, поэтому мне придется включить ее обратно.
Заранее спасибо.

Подробнее здесь: https://stackoverflow.com/questions/793 ... ific-class
Ответить

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

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

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

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

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