JsonConvert.DeserializeObject error mvc asp.net newtonjson

I use HttpRequestMessage my model is some different VirtualStock. My API JSON model as below

[{
        "_id": "5f2d66ae6abb1d6870e926ac",
        "MessageId": "EAD8B97887FFC1F180F3005056BF2302",
        "MessageType": "CreateDiscount",
        "RequestedBy": "AAA",
        "RequestedDate": "2020-08-07T17:22:58.000Z",
        "Data": {
            "_id": "5f2d66ae6abb1d6870e926ad",
            "Sku": "A",
            "SkuId": "EAD8B97887FFC0F180F3005056BF2302",
            "Price": 1759.17,
            "PurchasePrice": 1768.88,
            "StartDateTime": "2020-08-07T17:24:34.000Z",
            "EndDateTime": "2020-09-01T00:00:00.000Z",
            "VirtualStock": "1000",
            "MaximumQuantityForCart": 10,
            "CurrencyCode": "949"
        },
        "__v": 0
    },
    {
        "_id": "5f2d65daf7168b686d9474b9",
        "MessageId": "EAD8B8F92D90CDF180F3005056BF2302",
        "MessageType": "UpdateDiscount",
        "RequestedBy": "AAA",
        "RequestedDate": "2020-08-07T17:19:26.000Z",
        "Data": {
            "_id": "5f2d65daf7168b686d9474c5",
            "Sku": "A",
            "SkuId": "EAD8B8F92D90C5F180F3005056BF2302",
            "DiscountId": "8c3975a0-ea85-48e9-9c31-ea488bdad5c4",
            "Price": 296.2,
            "PurchasePrice": 239.91,
            "StartDateTime": "2020-08-01T14:35:00.000Z",
            "EndDateTime": "2020-08-07T17:23:08.000Z",
            "VirtualStock": {
                "Value": "100",
                "IsAssigned": true
            },
            "MaximumQuantityForCart": 25,
            "CurrencyCode": "949"
        },
        "__v": 0
    }
]

I defined my model VirtualStock like object and nullable.

public object? VirtualStock { get; set; }

but I get error parsing how can fix this?

I saw with debug Deserialize Success but showing JSON GetDiscount method I have exceptions

controller code as below

public IActionResult Discount()
{
    return View();
}
public async Task<IActionResult> GetDiscount()
{
    return Json(new { data = await _log.GetAllAsync("http://0.0.0.0/DiscountLog?pagesize=9&page=16") });
}

my Repository

public async Task<IEnumerable<T>> GetAllAsync(string url)
{
    var request = new HttpRequestMessage(HttpMethod.Get, url);

    var client = _clientFactory.CreateClient();

    HttpResponseMessage response = await client.SendAsync(request);
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        var jsonString = await response.Content.ReadAsStringAsync();

        var jsonSerializerSettings = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };

        return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString,jsonSerializerSettings);
    }

    return null;
}

My error:

JsonConvert.DeserializeObject error mvc asp.net newtonjson

An unhandled exception occurred while processing the request.
NotSupportedException: The collection type ‘System.Object’ on
‘RetailLogWeb.Models.LogItem.VirtualStock’ is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)

NotSupportedException: The collection type ‘System.Object’ on
‘RetailLogWeb.Models.LogItem.VirtualStock’ is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonPropertyInfo.GetDictionaryKeyAndValue(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo
elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter
writer, ref WriteStack state)
System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, int
originalWriterDepth, int flushThreshold, JsonSerializerOptions
options, ref WriteStack state)
System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, object
value, Type inputType, JsonSerializerOptions options,
CancellationToken cancellationToken)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter,
TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next,
Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter,
TFilterAsync>(ref State next, ref Scope scope, ref object state, ref
bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State
next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

OP figured it out as shared in the comments, but I’ll provide an answer here just to close out the question. As explained in this answer, the solution was to add a variant of this line:

services.AddControllers().AddNewtonsoftJson();

This was needed because Newtonsoft.Json was removed during a recent upgrade to .NET Core, and this adds it back in. Note that this assumes you have the Microsoft.AspNetCore.Mvc.NewtonsoftJson package installed.

More info here.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x