Search code examples
c#jsondatacontractserializerdatacontract

From JSON string to object


I have a following valid json string:

var result = "[{\"total\":" + wpTotal + ",\"totalpages\":" + wpTotalPages + "},{\"tags\":[{\"id\":384},{\"id\":385}]}]";

I am trying to use this method to deserialize it to object of type T:

public static T FromJSON<T>(string json)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            var settings = new DataContractJsonSerializerSettings
            {
                UseSimpleDictionaryFormat = true
            };
            var serializer = new DataContractJsonSerializer(typeof(T), settings);
            return (T)serializer.ReadObject(ms);
        }
    }

And using it like this:

var obj = JsonHelper.FromJSON<TagsResponse>(result);

I am always getting empty result (null) without any exception or any kind of information.

My model is:

[DataContract]
public class TagsResponse
{
    [DataMember(Name = "total")]
    public int Total { get; set; }

    [DataMember(Name = "totalpages")]
    public int TotalPages { get; set; }

    [DataMember(Name = "tags")]
    public List<Tag> Tags { get; set; }
}

Where is the problem?


Solution

  • Something is wrong with the format of your input, the properties in the json string are not the expected level of your objects, here is a working example:

    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"total\":" + 1 + ",\"totalpages\":" + 10 + ",\"tags\":[{\"id\":384},{\"id\":385}]}";
            var result = json.FromJSON<TagsResponse>();
            Console.WriteLine("Hello World!" + result);
        }
    }
    
    public static class Helper
    {
        public static T FromJSON<T>(this string json)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                return (T)serializer.ReadObject(ms);
            }
        }
    }
    
    [DataContract]
    public class TagsResponse
    {
        [DataMember(Name = "total")]
        public int Total { get; set; }
    
        [DataMember(Name = "totalpages")]
        public int TotalPages { get; set; }
    
        [DataMember(Name = "tags")]
        public List<Tag> Tags { get; set; }
    }
    
    [DataContract]
    public class Tag
    {
        [DataMember(Name = "id")]
        public string Id { get; set; }
    }