我有一个来自Get Request的以下JSON文件:
{
"vcalendar": [
{
"version": "2.0",
"prodid": " CalendarID",
"vevent": [
{
"uid": " EventID",
"dtstamp": "20180725T000000",
"status": "CONFIRMED",
"dtstart": [
"20180213",
{
"value": "DATE"
}
],
"dtend": [
"20180214",
{
"value": "DATE"
}
],
"summary": " Event subject",
"description": "Event description"
}
]
}
],
"success": true
}
在这种情况下,我想获取dtstart和dtend原语编号为“ 20180213”和“ 20180214”,但是我无法按照通常的方式反序列化JSON文件以获取所需的信息。
要获取我使用的其他值:
public class iCalendarFile
{
public List<iCalendar> vcalendar { get; set; }
}
public class iCalendar
{
public List<iCalendarEvent> vevent { get; set; }
}
public class iCalendarEvent
{
public string summary { get; set; }
public string description { get; set; }
public List<string> dtstart { get; set; }
public List<string> dtend { get; set; }
}
然后反序列化:
public static async void makeGetRequest(TraceWriter log) {
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var result = reader.ReadToEnd();
var jsonObject = JsonConvert.DeserializeObject<iCalendarFile>(result);
foreach (iCalendar icalobject in jsonObject.vcalendar ) {
foreach (iCalendarEvent Object in icalobject.vevent)
{
foreach(String tmp in Object.dtstart){
log.Info(tmp);
}
}
}
reader.Close();
dataStream.Close();
response.Close();
}
我的错误是:
Newtonsoft.Json.JsonReaderException:解析值{时遇到意外字符。路径'vcalendar [0] .vevent [0] .dtstart [0]',第1行,位置238。 在Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType) 在Newtonsoft.Json.JsonTextReader.ReadAsString() 在Newtonsoft.Json.JsonReader.ReadForType(JsonContract合同,布尔值hasConverter)
如果您有任何想法如何在dtstart中访问值,我将不胜感激。感谢您的帮助!
答案 0 :(得分:0)
在第一次更改时,JSON类(https://jsonutils.com/)
#region JsonClass
public class Vevent
{
public string uid { get; set; }
public string dtstamp { get; set; }
public string status { get; set; }
public IList<object> dtstart { get; set; }
public IList<object> dtend { get; set; }
public string summary { get; set; }
public string description { get; set; }
}
public class Vcalendar
{
public string version { get; set; }
public string prodid { get; set; }
public IList<Vevent> vevent { get; set; }
}
public class iCalendarFile
{
public IList<Vcalendar> vcalendar { get; set; }
public bool success { get; set; }
}
#endregion
之后,您可以:
var jsonObject = JsonConvert.DeserializeObject<iCalendarFile>(sb);
for (int i = 0; i < jsonObject.vcalendar[0].vevent[0].dtstart.Count; i++)
{
Console.WriteLine(jsonObject.vcalendar[0].vevent[0].dtstart[i].ToString());
}
答案 1 :(得分:0)
dtstart和dtend变量不能反序列化为字符串。
请尝试将变量从List<string>
更改为List<object>
答案 2 :(得分:0)
如果仅需要dtstart / dtend值,则可以尝试以下操作:
dynamic jsonObject = JsonConvert.DeserializeObject(result);
string dtstart = jsonObject.vcalendar[0].vevent[0].dtstart[0];
string dtend = jsonObject.vcalendar[0].vevent[0].dtstart[0];