简体   繁体   English

Json序列化为空

[英]Json Serializing to Null

I haven't had much need for Json, so it's still at that head-banging degree of frustration for me. 我对Json的需求不是很大,所以对我来说仍然处于那种令人头疼的挫败感。 I apologize if this is a dupe, but everything I found in searches had to do with different issues. 对于这是骗子,我深表歉意,但我在搜索中发现的所有内容都与其他问题有关。

I'm trying to use the Walmart API, and my data is coming through fine (I've attached a single record below for reference). 我正在尝试使用Walmart API,并且我的数据很好(我在下面附加了一条记录供参考)。 All the existing questions I can find seem to deal with null data coming in. This is about null data going out. 我能找到的所有现有问题似乎都与传入的空数据有关。这是关于空数据流出的问题。

Problem/Question: My call to the API results in a huge return - in the 1,000's of records (385MB uncompressed). 问题/疑问:我对API的调用产生了巨大的回报-记录数为1000(未压缩为385MB)。 When I deserialize, I get no exception and I still get 1000's of records, but each property in the returned list is null or 0. So, Json returns a list of generics and the list has records and the records are not null, but all of the values/properties inside each records are null (or 0 if numeric). 当我反序列化时,我也没有异常,仍然得到1000条记录,但是返回列表中的每个属性为null或0。因此,Json返回了一个泛型列表,该列表具有记录,并且记录也不为null,但是所有每个记录内的值/属性的值均为null(如果为数字,则为0)。

I've set a breakpoint in the serialization process, and I can see the json data coming in correctly. 我在序列化过程中设置了一个断点,并且可以看到json数据正确输入。 It's just coming out as null/0. 它只是以null / 0的形式出现。

If you have any ideas - I'd really appreciate any help you can provide. 如果您有任何想法-非常感谢您可以提供的任何帮助。 Thank you for your time in reading this, and in advance for any assistance you can provide. 感谢您抽出宝贵的时间阅读本文,并感谢您提供的任何帮助。

Undesired Result: 不良结果:

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

Serialization Logic: 序列化逻辑:

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

Sample Json Record: 样本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 Class: 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; }
    }
}

You should add [DataMember] attribute to properties in Item class. 您应该将[DataMember]属性添加到Item类的属性中。 Right now only Items list is "detected", and Item obcject are serialized with default values 现在,只有“项目”列表被“检测到”,并且项目对象被序列化为默认值

Step 1: 第1步:

Plop your JSON down in this site, to build your C# POCO model ( http://json2csharp.com/ ) 在此站点中放入JSON,以构建C#POCO模型( http://json2csharp.com/

Step 2: 第2步:

Get Json.Net from Newtonsoft. 从Newtonsoft获取Json.Net。

Step 3: 第三步:

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

To go back the other way simply: 要简单地返回另一种方式:

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

Step 4: 第四步:

Read all about Json.Net, because it is far superior to anything else for dealing with JSON in .Net. 阅读有关Json.Net的所有内容,因为它在处理.Net中的JSON方面比其他任何东西都要优越。 Also if you're feeling adventurous, read about the dynamic type if you already haven't. 另外,如果您喜欢冒险,请阅读动态类型(如果您还没有的话)。 Json.Net and the dynamic type in C# = a whole lot less code to do the same things. Json.Net和C#中的动态类型=更少的代码可以完成相同的操作。

Last thing. 最后一件事。 No need for any attributes, just have to have an empty constructor, or no constructor. 不需要任何属性,只需要一个空的构造函数,或者就不需要构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM