【问题标题】:Json Serializing to NullJson 序列化为 Null
【发布时间】:2016-09-09 21:54:21
【问题描述】:

我对 Json 的需求并不大,所以对我来说仍然是那种令人头疼的挫败感。如果这是一个骗局,我深表歉意,但我在搜索中发现的所有内容都与不同的问题有关。

我正在尝试使用 Walmart API,并且我的数据正常(我在下面附上了一条记录以供参考)。我能找到的所有现有问题似乎都处理传入的空数据。这是关于传出空数据的问题。

问题/问题:我对 API 的调用产生了巨大的回报 - 在 1,000 条记录中(385MB 未压缩)。当我反序列化时,我没有任何异常,我仍然得到 1000 条记录,但是返回列表中的每个属性都是 null 或 0。因此,Json 返回一个泛型列表,该列表有记录并且记录不为空,而是全部每个记录中的值/属性为空(如果为数字,则为 0)。

我在序列化过程中设置了断点,可以看到json数据正确传入。它只是以 null/0 的形式出现。

如果您有任何想法 - 非常感谢您提供的任何帮助。感谢您抽出宝贵时间阅读本文,并提前为您提供任何帮助。

不良结果:

Item_ID itemId  parentItemId    name    salePrice   upc shortDescription    longDescription brandName   thumbnailImage  mediumImage largeImage  productTrackingUrl  ninetySevenCentShipping standardShipRate    size    color   marketplace shipToStore freeShipToStore productUrl  customerRating  numReviews  customerRatingImage rollBack    bundle  clearance   stock   gender  age freeShippingOver50Dollars   availableOnline
 1  0   0   NULL    0   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    0   0   NULL    NULL    0   0   0   NULL    NULL    0   NULL    0   0   0   NULL    NULL    NULL    0   0

序列化逻辑:

public API_Json_Special_Feeds.RootObject testExistingJson()
    {
        string json = "";
        //I saved a response to a text file so I don't overload the API with testing. The same problem happens whether or not I load from API or text file.
        using(TextReader tr = new StreamReader(@"C:jsonsingle.txt"))
        {
            json = tr.ReadToEnd();//string
        }
        var serializer = new DataContractJsonSerializer(typeof(API_Json_Special_Feeds.RootObject));

        var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
        var data = (API_Json_Special_Feeds.RootObject)serializer.ReadObject(ms);
         return data;
    }

Json 记录示例:

 {"items":[ {
 "itemId" : 12321374,
 "parentItemId" : 12321374,
 "name" : "Castle Tent Loft Bed w/ Slide ; Under Bed Storage, Blue",
 "salePrice" : 369.0,
 "upc" : "081438383996",
 "shortDescription" : "Finished in White powder coat with Blue and Red Microfiber fabric tent",
 "longDescription" : "Fun Castle Tent Bunk Bed with Slide includes a tent over twin bed and a covered hiding place below. The covered hiding place below can also be used as under bed storage. The top of the slide is tented with a tower with peek through, fold down window covers. <ul class="noindent"><li>Finished in White powder coat with Blue and Red Microfiber fabric tent, 100% polyester.</li><li>Uses a standard twin size mattress (sold separately).</li><li>Only use a twin size mattress that is 74-75" long and 37.5-38.5" wide.</li><li>Bunk bed is tested and certified by an independent testing laboratory to meet all minimum requirements of ASTM F1427-07 and U.S. CFR 1213 and 1513.</li><li>Some assembly required. 79-3/4" x 101-1/4" x 92" tall.</li></ul>",
 "brandName" : "Castle",
 "thumbnailImage" : "https://i5.walmartimages.com/asr/a1bac83b-68f2-427e-82ac-97ce1e11b0c6_1.f18ff9fc14c7aca2d9c92c81f4b5c8ba.jpeg?odnHeight=100&odnWidth=100&odnBg=ffffff",
 "mediumImage" : "https://i5.walmartimages.com/asr/a1bac83b-68f2-427e-82ac-97ce1e11b0c6_1.f18ff9fc14c7aca2d9c92c81f4b5c8ba.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff",
 "largeImage" : "https://i5.walmartimages.com/asr/a1bac83b-68f2-427e-82ac-97ce1e11b0c6_1.f18ff9fc14c7aca2d9c92c81f4b5c8ba.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff",
 "productTrackingUrl" : "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=http%253A%252F%252Fwww.walmart.com%252Fip%252FCastle-Tent-Loft-Bed-w-Slide--Under-Bed-Storage-Blue%252F12321374%253Faffp1%253D%257Capk%257C%2526affilsrc%253Dapi",
 "ninetySevenCentShipping" : false,
 "standardShipRate" : 0.0,
 "size" : "Twin",
 "color" : "Blue",
 "marketplace" : false,
 "shipToStore" : true,
 "freeShipToStore" : true,
 "productUrl" : "http://c.affil.walmart.com/t/api00rb?l=http%3A%2F%2Fwww.walmart.com%2Fip%2FCastle-Tent-Loft-Bed-w-Slide--Under-Bed-Storage-Blue%2F12321374%3Faffp1%3D%7Capk%7C%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi",
 "customerRating" : "4.574",
 "numReviews" : 54,
 "customerRatingImage" : "http://i2.walmartimages.com/i/CustRating/4_6.gif",
 "rollBack" : true,
 "bundle" : true,
 "clearance" : false,
 "stock" : "Available",
 "gender" : "Boys",
 "age" : "Child",
 "freeShippingOver50Dollars" : true,
 "availableOnline" : true
}]
}

Json 类:

public class API_Json_Special_Feeds
{
    [DataContract]
    public class Item
    {
        public int itemId { get; set; }
        public int parentItemId { get; set; }
        public string name { get; set; }
        public double salePrice { get; set; }
        public string upc { get; set; }
        public string shortDescription { get; set; }
        public string longDescription { get; set; }
        public string brandName { get; set; }
        public string thumbnailImage { get; set; }
        public string mediumImage { get; set; }
        public string largeImage { get; set; }
        public string productTrackingUrl { get; set; }
        public bool ninetySevenCentShipping { get; set; }
        public double standardShipRate { get; set; }
        public string size { get; set; }
        public string color { get; set; }
        public bool marketplace { get; set; }
        public bool shipToStore { get; set; }
        public bool freeShipToStore { get; set; }
        public string productUrl { get; set; }
        public string customerRating { get; set; }
        public int numReviews { get; set; }
        public string customerRatingImage { get; set; }
        public bool rollBack { get; set; }
        public bool bundle { get; set; }
        public bool clearance { get; set; }
        public string stock { get; set; }
        public string gender { get; set; }
        public string age { get; set; }
        public bool freeShippingOver50Dollars { get; set; }
        public bool availableOnline { get; set; }
    }
    [DataContract]
    public class RootObject
    {
        [DataMember]
        public List<Item> items { get; set; }
    }
}

【问题讨论】:

    标签: c# json json-deserialization


    【解决方案1】:

    您应该在 Item 类的属性中添加[DataMember] 属性。 现在只有 Items 列表被“检测到”,并且 Item 对象被序列化为默认值

    【讨论】:

    • 哎呀!你说的完全正确!完全脑放屁。去改变...
    • 做到了!我正在使用其中一个剪切和粘贴站点来创建类,并且由于某种原因它没有添加属性。我太新了,无法注意到差异。希望我在三个小时前发布,而不是针对这个问题抨击我的头骨。我真的很欣赏你的鹰眼!很棒的第一个答案!
    【解决方案2】:

    第 1 步:

    将您的 JSON 放入此站点,以构建您的 C# POCO 模型 (http://json2csharp.com/)

    第 2 步:

    从 Newtonsoft 获取 Json.Net。

    第 3 步:

    RootObject myObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
    

    简单地回到另一条路:

    string jsonString = JsonConvert.SerializeObject<RootObject>(myObject);
    

    第 4 步:

    阅读有关 Json.Net 的所有信息,因为它在处理 .Net 中的 JSON 方面远远优于其他任何东西。此外,如果您喜欢冒险,请阅读动态类型(如果您还没有的话)。 Json.Net 和 C# 中的动态类型 = 做同样事情的代码要少得多。

    最后一件事。不需要任何属性,只需要有一个空的构造函数,或者没有构造函数。

    【讨论】:

    • 我真的很感激。我将反序列化方法的最后一行更改为 return JsonConvert.DeserializeObject(json);仍然得到 0/null,但正如另一个答案表明我需要添加更多数据成员。一旦我这样做,我肯定会使用你的建议。非常感谢!
    • 虽然我同意这是最好的方法,但 [DataMember] 属性是所提问题的正确答案。另外作为旁注,您不需要该网站从 JSON 生成 POCO 类,在 Visual Studio 本身中,您可以转到 Edit > Paste Special > JSON as Classes,这将从您拥有的任何 JSON 字符串生成所需的所有类剪贴板。
    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 2017-12-14
    • 2017-06-02
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多