[英]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. 我有一个表示开始时间和结束时间的jSON字符串,我正在尝试在c#中反序列化该字符串,以计算出时间跨度。
The jSON string is built as follows: jSON字符串的构建如下:
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: 并返回一个字符串(在
Context.Response.Write
选中此字符串),如:
"{"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'" 当我调用
getTimes
(通过下拉列表选择的值提供的int user
)时,出现错误:“'string'不包含'startTime'的定义”
My code for calling getTimes
is: 我调用
getTimes
代码是:
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? 我感到困惑,因为我认为它应该反序列化jSON并给我正确的结果? 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 = """;
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) ... 典型用法(TimeSpans可能比DateTimes更适合您的情况)...
var foo = { starttime = Datetime.UtcNow, endTime = DateTime.UtcNow.AddHours(1) };
var json = JsonConvert.SerializeObject(foo);
var bar = JsonConvert.DeSerializeObject(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.