user13731217
user13731217

Reputation:

Json Deserializer in C# is returning Incorrect Values from Json Request Response

I am attempting to return the Json response deserialized from the following https://www.supremenewyork.com/mobile_stock.json

Below is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using System.Drawing;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using RestSharp;
using System.Threading.Tasks;
using System.Globalization;

namespace SupremeMobileMonitor
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var program = new Program();
            await program.GetItem();

        }
        // Declaring variables in the list
        static List<ItemDetail> ProductList = new List<ItemDetail>();
        List<string> productDesc = new List<string> { "new_item", "price", "category", "imageurl", "itemURL" };
        List<string> category = new List<string> { "jackets", "shirts", "tops_sweaters", "pants", "hats", "accessories", "shoes", "skate" };

        //creating a class for intializing Json Deserializer 

        public class MobileStockResponse
    {
        [JsonProperty("unique_image_url_prefixes")]
        public List<object> UniqueImageUrlPrefixes { get; set; }

        [JsonProperty("products_and_categories")]
        public Dictionary<string, List<ProductsAndCategory>> ProductsAndCategories { get; set; }

        [JsonProperty("release_date")]
        public string ReleaseDate { get; set; }

        [JsonProperty("release_week")]
        public string ReleaseWeek { get; set; }
    }
        public partial class ProductsAndCategory
        {
            [JsonProperty("name")]
            public string Name { get; set; }
            [JsonProperty("id")]
            public long Id { get; set; }
            [JsonProperty("image_url")]
            public string ImageUrl { get; set; }
            [JsonProperty("image_url_hi")]
            public string ImageUrlHi { get; set; }
            [JsonProperty("price")]
            public long Price { get; set; }
            [JsonProperty("sale_price")]
            public long SalePrice { get; set; }
            [JsonProperty("new_item")]
            public bool NewItem { get; set; }
            [JsonProperty("position")]
            public long Position { get; set; }
            [JsonProperty("category_name")]
            public string CategoryName { get; set; }


        }


        //Initializing HttpClient for Requests and po
        public async Task GetItem()
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri("https://www.supremenewyork.com/mobile_stock.json"),
                Method = HttpMethod.Get
            };
            var response = await client.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();
            var responseObject = JsonConvert.DeserializeObject<ProductsAndCategory>(responseContent);

            Console.WriteLine(responseObject);




        }



    }
}

When I try to return a value (example: responseObject.id) It will just return '0'

When I try to return the complete response, it returns "SupremeMobileMonitor.Program+ProductsAndCategory"

Any idea why I can't get it returned and what I'm messing up my deserialization? Unfortunately the category known as "new" on the endpoint interferes with the C# keywords therefore removing my option to use dynamic deserialization.

Upvotes: 1

Views: 766

Answers (2)

Jawad
Jawad

Reputation: 11364

jslowik has the correct answer for your question, how to deserialize it.

To Print the object, you can either create an override ToString() method and print out only the things you are interested in, or you can print the object by serializing it to a string.

Console.WriteLine(JsonConvert.SerializeObject(productsAndCategories, Formatting.Indented);

This will give you a json representation again of the object and show you all the values.

SideNote: If you want to get specific items from, Say, Bags, you can use Linq to get it...

Console.WriteLine(JsonConvert.SerializeObject(responseObject.ProductsAndCategories["Bags"].Select(x => x.Id)));

// Output:
[173389,172978,173019,172974,173018,173001]

Upvotes: 1

jslowik
jslowik

Reputation: 161

Off hand I would just deserialize the full object. Example:

// Full model represented by your class
var responseObject = JsonConvert.DeserializeObject<MobileStockResponse>(responseContent);

// The products and categories dictionaries you're looking for
var productsAndCategories = responseObject.ProductsAndCategories;

Upvotes: 1

Related Questions