Vaibhav Ghorpade
Vaibhav Ghorpade

Reputation: 108

Parse JSON string to dynamic object without creating class using System.Runtime.Serialization.Json

The JSON string that I want to parse is the response from the API and the response may not have fixed properties. So cannot create a class with properties to parse the JSON string.

I tried to parse the JSON string to dynamic/Expando object but it does not parse the nested objects,

For example,

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

I am using the below code for deserializing the JSON string,

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);

This code fails to parse the Address property. It simply shows the object instead of the actual value.

enter image description here

Due to project requirement cannot use NewtonsoftJSON and System.Text.Json.

How I can parse complex JSON string to dynamic object without creating a custom class using System.Runtime.Serialization.Json?

Upvotes: 0

Views: 265

Answers (0)

Related Questions