简体   繁体   中英

c# jSON.net - unable to parse deserialized string - string does not contain definition for x

I have a jSON string representing a start and end time, which I am trying to deserialize in c# in order to work out the timespan.

The jSON string is built as follows:

private string getTimes(int user)
{
    string jSON = "";
    string x = """;
    switch(user)
    {
        case 1:
            jSON = "{'startTime':08:00,'endTime':'16:00'}".Replace("'",x);
            break;
        case 2:
            jSON = "{'startTime':09:00,'endTime':'17:00'}".Replace("'", x);
            break;
        case 3:
            jSON = "{'startTime':12:00,'endTime':'20:00'}".Replace("'", x); ;
        break;
    }
    jSON = JsonConvert.SerializeObject(jSON);
    return jSON;
}

and it returns a string (checked this in Context.Response.Write ) like:

"{"startTime":12:00,"endTime":20:00}"

When I call getTimes ( int user supplied via a dropdownlist selected value) I get an error: "'string' does not contain a definition for 'startTime'"

My code for calling getTimes is:

int user = int.Parse(ddlUser.SelectedValue);
    string timesInJSON = getTimes(user);

    var results = JsonConvert.DeserializeObject<dynamic>(timesInJSON);
    DateTime dtStart = Convert.ToDateTime(results.startTime);
    DateTime dtEnd = Convert.ToDateTime(results.endTime);

I'm confused as I thought it should deserialize the jSON and give me the right result? What am I missing/doing wrong?

It seems you are trying to serialize a string? You serialize objects to get a string.

private string getTimes(int user)
{
    string jSON = "";
    string x = "&quot;";
    switch(user)
    {
        case 1:
            jSON = "{'startTime':08:00,'endTime':'16:00'}".Replace("'",x);
            break;
        case 2:
            jSON = "{'startTime':09:00,'endTime':'17:00'}".Replace("'", x);
            break;
        case 3:
            jSON = "{'startTime':12:00,'endTime':'20:00'}".Replace("'", x); ;
        break;
    }
    //jSON = JsonConvert.SerializeObject(jSON);
    return jSON; //<-- already serialised
}

Typical usage (TimeSpans might be betterfor your situation though instead of DateTimes) ...

var foo = { starttime = Datetime.UtcNow, endTime = DateTime.UtcNow.AddHours(1) };
var json = JsonConvert.SerializeObject(foo);
var bar = JsonConvert.DeSerializeObject(json);

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