使用 System.Runtime.Serialization.Json 在不创建类的情况下将 JSON 字符串解析为动态对象

问题描述

我要解析的 JSON 字符串是来自 API 的响应,该响应可能没有固定的属性。因此无法创建具有属性的类来解析 JSON 字符串。

我尝试将 JSON 字符串解析为动态/Expando 对象,但它没有解析嵌套对象,

例如

string jsonText = "[{ \"FirstName\":\"John\",\"LastName\":\"K\",\"Address\":{\"Line1\":\"Sector 6\"} }]";

我使用以下代码反序列化 JSON 字符串,

public static T Deserialize<T>(this string str) where T : class
        {
            var ser = new DataContractJsonSerializer(typeof(T),new DataContractJsonSerializerSettings
            {
                UseSimpleDictionaryFormat = true,IgnoreExtensionDataObject=true
                
            });
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {
                return (T)ser.Readobject(ms);
            }
        }

IEnumerable<ExpandoObject> contactObject = Deserialize<IEnumerable<ExpandoObject>>(jsonText);

代码无法解析 Address 属性。它只是显示对象而不是实际值。

enter image description here

由于项目要求不能使用 NewtonsoftJSON 和 System.Text.Json。

如何在不使用 System.Runtime.Serialization.Json 创建自定义类的情况下将复杂的 JSON 字符串解析为动态对象?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)