JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET

Home Page:https://www.newtonsoft.com/json

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Json data parsing in MAUI .NET 8

IXChinmayD opened this issue · comments

Initially, in Xamarin Forms, we were using response.ToObject() for JSON parsing. Here is the code snippet for your reference
(response.ResponseData).ToObject<DataDTO>()
But in .NET 8 it was giving error

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Text.Json.JsonElement' does not contain a definition for 'ToObject''

Hence we tried the following generic method to avoid code repetition in .NET MAUI.

using System.Text.Json;
public static T DeserializeTheObject<T>(dynamic responseData)
  {
      return JsonSerializer.Deserialize<T>(responseData, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true, // Ensure case-insensitive deserialization
                PropertyNamingPolicy = null,
                Converters = {
                        new JsonStringEnumConverter()
                    }
            });
  }

using System.Text.Json;
public static List<T> DeserializeJsonArrayList<T>(dynamic responseData)
 {
     return JsonSerializer.Deserialize<List<T>>(responseData, new JsonSerializerOptions
           {
               PropertyNameCaseInsensitive = true, // Ensure case-insensitive deserialization
               PropertyNamingPolicy = null,
               Converters = {
                       new JsonStringEnumConverter()
                   }
           });
 }

This code works fine in Android in debug mode but the app crashes in release mode giving the below error

Xamarin Exception Stack:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: BadArgTypes
  at System.Object.CallSite.Target(Closure , CallSite , Type , Object , JsonSerializerOptions )
  at System.Dynamic.UpdateDelegates.UpdateAndExecute3[Type,Object,JsonSerializerOptions,Object](CallSite site, Type arg0, Object arg1, JsonSerializerOptions arg2)