简体   繁体   中英

String was not recognized as a valid DateTime while converting json to objects

I am trying to de-serialize a json object but getting this error, here is my call code.

I am not exactly sure what has changed in my code, this use to work just fine before from what I remember.

var serializedCriteria = JsonConvert.SerializeObject(criteria, new RawJsonConverter());
var request = new HttpRequestMessage()
{
    RequestUri = new Uri($"{urlBase}/events/search"),
    Method = HttpMethod.Post,
    Content = new StringContent(serializedCriteria, Encoding.UTF8, "application/json"),


};

var response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;

var serializer = new DataContractJsonSerializer(typeof(RootObject), new DataContractJsonSerializerSettings
{
     DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
});

var root = serializer.ReadObject(await response.Content.ReadAsStreamAsync()) as RootObject;
return root;

Here is my JsonConverter if it makes any diff,

public class RawJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue(value.ToString());
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(string).IsAssignableFrom(objectType);
    }

    public override bool CanRead
    {
        get { return false; }
    }
}

Here are my classes

public class Event
{
    public int eventId { get; set; }
    public string title { get; set; }
    public DateTime startDateTimeUTC { get; set; }
    public DateTime endDateTimeUTC { get; set; }
    public int categoryId { get; set; }
    public Category category { get; set; }
    public string summary { get; set; }
    public bool isApproved { get; set; }
    public string sourceURL { get; set; }
    public string timeZoneID { get; set; }
    public string coinSymbol { get; set; }
    public string sourceUrlBase { get; set; }
    public int countDownNumber { get; set; }
    public string countDownString { get; set; }
    public string fullEventDateString { get; set; }
    public DateTime endDateTimeLocal { get; set; }
    public DateTime startDateTimeLocal { get; set; }
}

public class Range
{
    public string backgroundColor { get; set; }
    public string title { get; set; }
    public List<Event> events { get; set; }
    public int count { get; set; }
}

public class RootObject
{
    public List<Range> ranges { get; set; }
    public int totalEvents { get; set; }
}

And finally here is the json that is returned by the api call and trying to de-serialize

{
"ranges": [
    {
        "backgroundColor": "blue",
        "title": "Happening Now",
        "events": [
            {
                "eventId": 1032,
                "title": "EquiTrader Private Alpha Invite only by October 2017",
                "startDateTimeUTC": "2017-09-30T23:00:00",
                "endDateTimeUTC": "2017-10-31T23:59:00",
                "categoryId": 3,
                "category": {
                    "categoryId": 3,
                    "description": "Software/Platform"
                },
                "summary": "Private Alpha Invite only by October 2017.    Trade via telegram and view the positions on telegram #Revolution",
                "isApproved": true,
                "sourceURL": "https://twitter.com/Equi_Trader/status/908030030076358671",
                "timeZoneID": "GMT Standard Time",
                "coinSymbol": null,
                "sourceUrlBase": "https://twitter.com",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 01, 2017 12:00 AM - October 31, 2017 11:59 PM",
                "endDateTimeLocal": "2017-10-31T23:59:00",
                "startDateTimeLocal": "2017-10-01T00:00:00"
            },

            {
                "eventId": 2112,
                "title": "A Charitable Crypto-Currency",
                "startDateTimeUTC": "2017-10-21T00:00:00",
                "endDateTimeUTC": "2018-01-21T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "CCCoin is a charitable crypto-currency that raises capital through currency exchanges and donates the proceeds to notable trusted charities chosen through a democratic voting process using secure transparent blockchain technology.",
                "isApproved": true,
                "sourceURL": "https://www.cccoin.io/",
                "timeZoneID": "UTC",
                "coinSymbol": "CCC",
                "sourceUrlBase": "https://www.cccoin.io",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 21, 2017 12:00 AM - January 21, 2018 11:59 PM",
                "endDateTimeLocal": "2018-01-21T23:59:00Z",
                "startDateTimeLocal": "2017-10-21T00:00:00Z"
            },
            {
                "eventId": 2113,
                "title": "AI economies on the blockchain",
                "startDateTimeUTC": "2017-10-21T00:00:00",
                "endDateTimeUTC": "2017-11-21T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "Synapse is creating a decentralized data and machine learning marketplace and exchange. This will allow anyone to contribute data, train machine learning models, and be compensated for both.",
                "isApproved": true,
                "sourceURL": "https://synapse.ai/",
                "timeZoneID": "UTC",
                "coinSymbol": "SYN",
                "sourceUrlBase": "https://synapse.ai",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 21, 2017 12:00 AM - November 21, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-21T23:59:00Z",
                "startDateTimeLocal": "2017-10-21T00:00:00Z"
            },
            {
                "eventId": 2114,
                "title": "Cooperative Ownership Platform for Real Assets",
                "startDateTimeUTC": "2017-10-21T00:00:00",
                "endDateTimeUTC": "2017-10-27T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "Swarm Fund is a fully decentralized capital market place that democratizes investing by using the power of the blockchain to open up high-return, alternative investment classes to smaller investors through asset-backed funds using cryptocurrency tokens. It makes traditionally exclusive investment opportunities, such as private equity and hedge funds, inclusive for the Swarm by pooling together smaller investments into larger, institutional-sized blocks. Swarm Fund also gives fund managers access to more capital from a new asset class of investors who want access to institutional-type investments, but don’t have the high minimums many institutional funds require. Pilot investment vehicles on the Swarm Fund platform include a Distressed Real Estate Fund, a Solar Energy Fund, and a Crypto Hedge Fund.",
                "isApproved": true,
                "sourceURL": "https://swarm.fund/",
                "timeZoneID": "UTC",
                "coinSymbol": "SWARM",
                "sourceUrlBase": "https://swarm.fund",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 21, 2017 12:00 AM - October 27, 2017 11:59 PM",
                "endDateTimeLocal": "2017-10-27T23:59:00Z",
                "startDateTimeLocal": "2017-10-21T00:00:00Z"
            },
            {
                "eventId": 2115,
                "title": "Financial instruments on ERC20 tokens",
                "startDateTimeUTC": "2017-10-22T00:00:00",
                "endDateTimeUTC": "2017-11-22T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "WandX is a decentralized platform on the Ethereum blockchain which enables users to create, trade, and settle any financial instrument on crypto-assets. Using the Wand Token, users can invest in ETFs (Exchange Traded Funds), buy cryptocurrency futures, and trade in illiquid assets through a portfolio of assets.",
                "isApproved": true,
                "sourceURL": "https://wandx.co/",
                "timeZoneID": "UTC",
                "coinSymbol": "WAND",
                "sourceUrlBase": "https://wandx.co",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 22, 2017 12:00 AM - November 22, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-22T23:59:00Z",
                "startDateTimeLocal": "2017-10-22T00:00:00Z"
            },
            {
                "eventId": 2116,
                "title": "Environmental Sustainability Solutions",
                "startDateTimeUTC": "2017-10-23T00:00:00",
                "endDateTimeUTC": "2017-11-20T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "A decentralised Natural Asset Exchange blockchain platform with accompanying Earth Token (EARTH) allows stakeholders in the climate value chain to explore vast untapped market segments including Natural Capital - the world's stock of natural resources. The untapped and undervalued Natural Capital asset class is estimated to be worth in excess of USD $120 trillion, yet no transparent mechanism exists to connect producers of Natural Assets with business, consumers, or IoT devices. The establishment of a Natural Asset Exchange blockchain platform with the Earth Token as the settlement mechanism currency will fuel demand side applications including Carbon Mitigation, Climate Neutral Fuel and Waste-to-Energy, offering unique environmental sustainability solutions and the creation of differentiated value for stakeholders to build brand equity and increase market share.",
                "isApproved": true,
                "sourceURL": "https://earth-token.com/",
                "timeZoneID": "UTC",
                "coinSymbol": "EARTH",
                "sourceUrlBase": "https://earth-token.com",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 23, 2017 12:00 AM - November 20, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-20T23:59:00Z",
                "startDateTimeLocal": "2017-10-23T00:00:00Z"
            },
            {
                "eventId": 2117,
                "title": "Smart Trading Bots",
                "startDateTimeUTC": "2017-10-23T00:00:00",
                "endDateTimeUTC": "2017-11-23T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "Solution of QPaas (Quantitative Performance as a Service) dedicated to cryptocurrencies holders, through the creation of an open online computer driven asset management platform selecting quantitative strategies (trading bots) from world class traders, where each crypto-fund dedicated to a specific Asset Class shall enhance the traditional model by improving its governance through smart contracts’ implementation.",
                "isApproved": true,
                "sourceURL": "https://www.napoleonx.ai/",
                "timeZoneID": "UTC",
                "coinSymbol": "NPX",
                "sourceUrlBase": "https://www.napoleonx.ai",
                "countDownNumber": 0,
                "countDownString": "Now",
                "fullEventDateString": "October 23, 2017 12:00 AM - November 23, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-23T23:59:00Z",
                "startDateTimeLocal": "2017-10-23T00:00:00Z"
            }
        ],
        "count": 13
    },
    {
        "backgroundColor": "slate",
        "title": "Next 7 Days",
        "events": [
            {
                "eventId": 2108,
                "title": "Powerful Identity based on blockchain",
                "startDateTimeUTC": "2017-10-25T00:00:00",
                "endDateTimeUTC": "2017-11-30T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "Verif-y’s identity solution addresses the fact that a strong and reliable digital identity is necessary for the continued expansion of the global digital economy and a fundamental building block of the rapidly expanding blockchain economy. To meet this fast-growing identification demand, Verif-y is expanding the development of the blockchain-based, digital identity solution layer of its commercially available credential and employment verification platform. Verif-y’s services improve the protection of Personally Identifiable Information (\"PII\"), which in today’s world define our identity. Verif-y gives its users the power to own, manage and communicate their digital identities and verified credentials, and gives entities an interface and layer of trust to provide and request PII data. Importantly, with Verif-y, all communication of PII is exclusively governed by the users, something not available until now. Verif-y brings value and efficiencies to all parties who participate in the ecosystem: educators, employers, credential providers, licensors, member organizations, certificate providers and lastly, but not least the users.",
                "isApproved": true,
                "sourceURL": "https://www.verif-y.io/",
                "timeZoneID": "UTC",
                "coinSymbol": "VFY",
                "sourceUrlBase": "https://www.verif-y.io",
                "countDownNumber": 3,
                "countDownString": "Hours",
                "fullEventDateString": "October 25, 2017 12:00 AM - November 30, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-30T23:59:00Z",
                "startDateTimeLocal": "2017-10-25T00:00:00Z"
            },
            {
                "eventId": 2068,
                "title": "EMC2 Hard Fork",
                "startDateTimeUTC": "2017-10-25T12:00:00",
                "endDateTimeUTC": "2017-12-01T12:00:00",
                "categoryId": 5,
                "category": {
                    "categoryId": 5,
                    "description": "Blockchain"
                },
                "summary": "EMC2 Hard Fork",
                "isApproved": true,
                "sourceURL": "http://www.altcointoday.com/bitcoin-gold-hard-fork/",
                "timeZoneID": "Dateline Standard Time",
                "coinSymbol": "BTC",
                "sourceUrlBase": "http://www.altcointoday.com",
                "countDownNumber": 15,
                "countDownString": "Hours",
                "fullEventDateString": "October 25, 2017 12:00 AM - December 01, 2017 12:00 AM",
                "endDateTimeLocal": "2017-12-01T00:00:00",
                "startDateTimeLocal": "2017-10-25T00:00:00"
            },
            {
                "eventId": 2063,
                "title": "Global Fintech & Blockchain China Summit",
                "startDateTimeUTC": "2017-10-25T16:00:00",
                "endDateTimeUTC": "2017-10-26T15:59:00",
                "categoryId": 4,
                "category": {
                    "categoryId": 4,
                    "description": "Conference"
                },
                "summary": "With the large data, cloud computing, block chain, artificial intelligence, mobile Internet and other information technology in the financial industry in-depth application, financial and technological depth of integration and traditional gold and Internet financial depth of cooperation Fintec3.0 era has arrived. FinTech is driving the transformation and upgrading of the traditional gold industry, but also gave birth to a number of new financial industry to flourish. Financial innovation, such as mobile payment, digital currency, P2P network loan, equity information, large data credit, intelligent investment, wisdom contract, scene finance and so on, are improving the efficiency of financial services and reducing the overall cost. Financial ecology. In particular, with the rapid development of block chain technology research and development and application of the chain has become Fintech3.0 era of technology engine, IBM released research report shows that by the end of 2017, 15% of banks will be involved in the block chain Technology, and in the next three years, nearly two-thirds of banks will be able to provide formal block-chain services. In addition, with the opening of the block chain 3.0, the application of the block chain is more extensive, gradually from the financial sector to the supply chain, energy, medical, government governance and other aspects, even in the future and artificial intelligence, Cross docking. This round of new wave of innovation, how to preempt the layout and application of block-chain technology to achieve the technical landing to obtain strategic advantages, which is not only the financial industry, but also a lot of chain chain + industry's top priority.",
                "isApproved": true,
                "sourceURL": "http://news.blockchain.hk/first-global-fintech-blockchain-conference-hold-in-shanghai/",
                "timeZoneID": "China Standard Time",
                "coinSymbol": "",
                "sourceUrlBase": "http://news.blockchain.hk",
                "countDownNumber": 19,
                "countDownString": "Hours",
                "fullEventDateString": "October 26, 2017 12:00 AM - 11:59 PM",
                "endDateTimeLocal": "2017-10-26T23:59:00",
                "startDateTimeLocal": "2017-10-26T00:00:00"
            },
            {
                "eventId": 1033,
                "title": "OKCoin will stop CNY to CryptoCurrency trading services",
                "startDateTimeUTC": "2017-10-30T16:00:00",
                "endDateTimeUTC": "2017-10-31T15:59:00",
                "categoryId": 1,
                "category": {
                    "categoryId": 1,
                    "description": "Exchange"
                },
                "summary": "People's Bank of China and other seven ministries issued a notice on the prevention of the risk of tokens issued financing, asked the financing of China's domestic currency and virtual currency transactions to make a comprehensive clean-up work, OKCoin This afternoon officially received the notice and guidance of the regulatory authorities. OKCoin Banks, a comprehensive digital asset trading platform that serves millions of users worldwide, has been working on technology and product innovation since 2013 to promote the healthy development of the chain and digital currency industries. The better service to the majority of users, we feel the shoulder of the historical mission, through four years of continuous struggle and contribution, we have made a lot of user trust, OK people have been so proud! In terms of business compliance, the OKCoin Bank is doing its best to respond positively to national regulation and to fulfill its obligations, and to actively propose and explore regulatory recommtions and programs aimed at protecting the interests of users. A decision is not the end, but a new start, the industry is more healthy and more compliant development of the beginning, OKCoin currency line will continue under the premise of compliance, for the customer service. Specific arrangements are as follows: First, the registration, recharge business arrangements 1, immediately from 20:30 on September 15, 21:30, OKCoin currency line to suspend registration, RMB recharge business, please do not continue to recharge RMB to OKCoin currency line. 2, because the customer service phone and online consultation queuing more, if you have questions about the recharge business, please send the relevant information to service@okcoin.com, customer service will be as soon as possible to reply to you. 3, the currency, to mention the currency, to mention the current are not affected. Second, to bring business arrangements 1, OKCoin Bank line adhere to the implementation of 100% reserve system",
                "isApproved": true,
                "sourceURL": "https://www.okcoin.cn/t-2510731.html",
                "timeZoneID": "China Standard Time",
                "coinSymbol": null,
                "sourceUrlBase": "https://www.okcoin.cn",
                "countDownNumber": 5,
                "countDownString": "Days",
                "fullEventDateString": "October 31, 2017 12:00 AM - 11:59 PM",
                "endDateTimeLocal": "2017-10-31T23:59:00",
                "startDateTimeLocal": "2017-10-31T00:00:00"
            },
            {
                "eventId": 1034,
                "title": "Huobi have announced to stop CNY to Cryptocurrency trading services ",
                "startDateTimeUTC": "2017-10-30T16:00:00",
                "endDateTimeUTC": "2017-10-31T15:59:00",
                "categoryId": 1,
                "category": {
                    "categoryId": 1,
                    "description": "Exchange"
                },
                "summary": "People's Bank of China and other seven ministries issued a notice on the prevention of the risk of tokens issued financing, asked the financing of China's domestic currency and virtual currency transactions to make a comprehensive clean-up work, OKCoin This afternoon officially received the notice and guidance of the regulatory authorities. OKCoin Banks, a comprehensive digital asset trading platform that serves millions of users worldwide, has been working on technology and product innovation since 2013 to promote the healthy development of the chain and digital currency industries. The better service to the majority of users, we feel the shoulder of the historical mission, through four years of continuous struggle and contribution, we have made a lot of user trust, OK people have been so proud! In terms of business compliance, the OKCoin Bank is doing its best to respond positively to national regulation and to fulfill its obligations, and to actively propose and explore regulatory recommtions and programs aimed at protecting the interests of users. A decision is not the end, but a new start, the industry is more healthy and more compliant development of the beginning, OKCoin currency line will continue under the premise of compliance, for the customer service. Specific arrangements are as follows: First, the registration, recharge business arrangements 1, immediately from 20:30 on September 15, 21:30, OKCoin currency line to suspend registration, RMB recharge business, please do not continue to recharge RMB to OKCoin currency line. 2, because the customer service phone and online consultation queuing more, if you have questions about the recharge business, please send the relevant information to service@okcoin.com, customer service will be as soon as possible to reply to you. 3, the currency, to mention the currency, to mention the current are not affected. Second, to bring business arrangements 1, OKCoin Bank line adhere to the implementation of 100% reserve system",
                "isApproved": true,
                "sourceURL": "https://www.huobi.com/p/content/notice/getNotice?id=641",
                "timeZoneID": "China Standard Time",
                "coinSymbol": null,
                "sourceUrlBase": "https://www.huobi.com",
                "countDownNumber": 5,
                "countDownString": "Days",
                "fullEventDateString": "October 31, 2017 12:00 AM - 11:59 PM",
                "endDateTimeLocal": "2017-10-31T23:59:00",
                "startDateTimeLocal": "2017-10-31T00:00:00"
            },
            {
                "eventId": 2106,
                "title": "Powering True Care",
                "startDateTimeUTC": "2017-10-31T00:00:00",
                "endDateTimeUTC": "2017-11-30T23:59:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "SimplyVital Health uses a Distributed Hash Table combined with an Ethereum base Blockchain to provide, among many other features, an ability for frictionless data sharing and access to new revenue streams. This is accomplished via an upgrade to data integrity and security system and the addition of an executive governance system for node validation. Their current platform in the market, ConnectingCare, is a realistic, practical utilization of blockchain technology. An intentionally simple introduction of blockchain technology into healthcare, this tool augments their current customers’ infrastructure using existing data to create care pathway flexibility, prospectively track financials, maintain immutable records, and accurately monitor analytics. Health Nexus propels healthcare infrastructure forward and, through the efficient and trustworthy ledger blockchain provides, empowers providers’ worldwide to transition to value based care regardless of their clinical affiliation. The simplicity of secure data sharing allows a patient’s entire care team, from surgeons to specialists, to coordinate the care every step of the way.",
                "isApproved": true,
                "sourceURL": "https://tokensale.simplyvitalhealth.com/",
                "timeZoneID": "UTC",
                "coinSymbol": "HLTH",
                "sourceUrlBase": "https://tokensale.simplyvitalhealth.com",
                "countDownNumber": 6,
                "countDownString": "Days",
                "fullEventDateString": "October 31, 2017 12:00 AM - November 30, 2017 11:59 PM",
                "endDateTimeLocal": "2017-11-30T23:59:00Z",
                "startDateTimeLocal": "2017-10-31T00:00:00Z"
            },
            {
                "eventId": 2071,
                "title": "Wcx 토큰",
                "startDateTimeUTC": "2017-10-31T12:07:00",
                "endDateTimeUTC": "2017-11-20T12:05:00",
                "categoryId": 2,
                "category": {
                    "categoryId": 2,
                    "description": "ICO/Pre-Sale"
                },
                "summary": "Http://wcex.co/?ref=YuU8f2ah\n",
                "isApproved": true,
                "sourceURL": "Ico.cex.co",
                "timeZoneID": "Dateline Standard Time",
                "coinSymbol": "Wcxt",
                "sourceUrlBase": "",
                "countDownNumber": 6,
                "countDownString": "Days",
                "fullEventDateString": "October 31, 2017 12:07 AM - November 20, 2017 12:05 AM",
                "endDateTimeLocal": "2017-11-20T00:05:00",
                "startDateTimeLocal": "2017-10-31T00:07:00"
            }
        ],
        "count": 7
    }
],
"totalEvents": 20
}

In your code, you are specifying the DateTimeFormat as yyyy-MM-dd'T'HH:mm:ss , but in the JSON not all the dates match that format exactly. In particular, some of the dates have a trailing Z (which is the Zulu (UTC) time zone indicator), while others do not.

If you change the DateTimeFormat to yyyy-MM-dd'T'HH:mm:ssK (note the trailing K specifier to represent a possible time zone), that should allow it to work with both formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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