【问题标题】:Json Deserializer in C# is returning Incorrect Values from Json Request ResponseC# 中的 Json 反序列化器从 Json 请求响应返回不正确的值
【发布时间】:2020-06-12 01:03:26
【问题描述】:

我正在尝试返回从以下 https://www.supremenewyork.com/mobile_stock.json 反序列化的 Json 响应

下面是我的代码:

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




        }



    }
}

当我尝试返回一个值时(例如:responseObject.id)它只会返回'0'

当我尝试返回完整响应时,它返回“SupremeMobileMonitor.Program+ProductsAndCategory”

知道为什么我无法返回它以及我在搞乱我的反序列化吗?不幸的是,端点上称为“新”的类别会干扰 C# 关键字,因此删除了我使用动态反序列化的选项。

【问题讨论】:

  • 是的,该类是基于我从 API 中提取的 json 创建的。
  • 或者你可以只序列化你刚刚反序列化的对象。那也行 :-D .... Jawad 打败了我。

标签: c# json json.net deserialization json-deserialization


【解决方案1】:

jslowik 对你的问题有正确的答案,如何反序列化它。

要打印对象,您可以创建覆盖ToString() 方法并仅打印出您感兴趣的内容,也可以通过将对象序列化为字符串来打印对象。

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

这将再次为您提供对象的 json 表示并显示所有值。

旁注:如果你想从 Say, Bags 中获取特定的项目,你可以使用 Linq 来获取它...

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

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

【讨论】:

    【解决方案2】:

    我只想反序列化整个对象。示例:

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

    【讨论】:

    • 使用Console.WriteLine(prodcutsAndCategories);时返回如下:System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[SupremeMobileMonitor.Program+ProductsAndCategory]]
    • 您无法真正查看这样的对象。设置断点并使用调试器,您应该会看到要查找的内容。此外,您不需要将产品和类别设置为离散变量。只是为了说明目的。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多