0

I have a json string that is being returned from HttpRequest that I am trying to deserialize to an object. The json has a root element that is not needed in my case (other applications that use the same data, need it so it can't be removed). I have tried several different ways to do this but my object is always null. I can see in the watch window that the json is being returned from the request correctly. Any ideas as to what I am missing?

My code is below.

Here is my object I am trying to deserialize to.

public class BrandHeaderResponse
{
    public BrandHeaderData brandHeaderData { get; set; }
}

public class BrandHeaderData
{
    public dynamic Image { get; set; } //url and alt text
    public string BackgroundColor { get; set; }
    public string LiveText { get; set; }
}

Here is the code

HttpResponseMessage response;
using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url)))
{
    response = await webClient.SendAsync(request, requestHeaders);
}
using (var stream = await response.Content.ReadAsStreamAsync())
{
    using (var sr = new StreamReader(stream))
    {
        using (var reader = new JsonTextReader(sr))
        {
            var serializer = new JsonSerializer();
            var data = serializer.Deserialize<T>(reader);
            return data;
        }
    }
}

And lastly, here is the json.

{  
   "2000_banner":{  
      "ComponentName":"2000_banner",
      "SchemaName":"Brand Banner",
      "BrandName":"Rockport - Dummy Banner",
      "LogoTextColor":"Dark",
      "Image":{  
         "ImageUrl":"http://n.media.com/staging/24?w=153&h=64",
         "AltText":"Burberry"
      },
      "LiveText":"This is dummy brand text for Rockport.",
      "BackgroundColor":"E3D9CE"
      }
  }
2
  • Will the property of the root object you want to deserialize always be named "2000_banner", or can the property name change? 2) Can there be other properties in the root object? Commented Jun 22, 2016 at 17:07
  • The name will change. It is based on the id of the object. I can serialize into a dictionary object and get my values from there but that seems a lot of overhead for a json string that will only ever contain one node (x_banner) We have a generic method that we use for all of our other json so I would like to be able to reuse it. For now, just so I am not stuck, I created a new method and deserialized to a dictionary. Commented Jun 22, 2016 at 17:52

1 Answer 1

1

I don't see any reason not to deserialize to a Dictionary<string, BrandHeaderData>, then set

new BrandHeaderResponse { brandHeaderData = dictionary.Values.SingleOrDefault() };

The overhead should be minimal

However, if for some reason you want to avoid that overhead, since you are already reading via a JsonTextReader, you can use the reader to iterate through the JSON stream until you find the first nested value, then deserialize that, using the following extension methods:

public static class JsonExtensions
{
    public static IEnumerable<T> DeserializeValues<T>(Stream stream)
    {
        var reader = new StreamReader(stream); // Caller should dispose
        return DeserializeValues<T>(reader);
    }

    public static IEnumerable<T> DeserializeValues<T>(TextReader textReader)
    {
        var ser = JsonSerializer.CreateDefault();
        var reader = new JsonTextReader(textReader); // Caller should dispose

        reader.SupportMultipleContent = true;

        while (reader.Read())
        {
            if (reader.Depth > 0
                && reader.TokenType != JsonToken.None && reader.TokenType != JsonToken.Undefined && reader.TokenType != JsonToken.PropertyName)
            {
                yield return ser.Deserialize<T>(reader);
            }
        }
    }
}

Then use DeserializeValues<BrandHeaderData>(stream).SingleOrDefault() to deserialize your JSON stream.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.