<i id='wNeD9'><tr id='wNeD9'><dt id='wNeD9'><q id='wNeD9'><span id='wNeD9'><b id='wNeD9'><form id='wNeD9'><ins id='wNeD9'></ins><ul id='wNeD9'></ul><sub id='wNeD9'></sub></form><legend id='wNeD9'></legend><bdo id='wNeD9'><pre id='wNeD9'><center id='wNeD9'></center></pre></bdo></b><th id='wNeD9'></th></span></q></dt></tr></i><div id='wNeD9'><tfoot id='wNeD9'></tfoot><dl id='wNeD9'><fieldset id='wNeD9'></fieldset></dl></div>

    <small id='wNeD9'></small><noframes id='wNeD9'>

      1. <legend id='wNeD9'><style id='wNeD9'><dir id='wNeD9'><q id='wNeD9'></q></dir></style></legend>
          <bdo id='wNeD9'></bdo><ul id='wNeD9'></ul>
      2. <tfoot id='wNeD9'></tfoot>

        如何使用 JSON.Net 转换新的日期(年、月、日)重载

        How to convert new Date(year, month, day) overload with JSON.Net(如何使用 JSON.Net 转换新的日期(年、月、日)重载)
        <tfoot id='148cP'></tfoot>

            <i id='148cP'><tr id='148cP'><dt id='148cP'><q id='148cP'><span id='148cP'><b id='148cP'><form id='148cP'><ins id='148cP'></ins><ul id='148cP'></ul><sub id='148cP'></sub></form><legend id='148cP'></legend><bdo id='148cP'><pre id='148cP'><center id='148cP'></center></pre></bdo></b><th id='148cP'></th></span></q></dt></tr></i><div id='148cP'><tfoot id='148cP'></tfoot><dl id='148cP'><fieldset id='148cP'></fieldset></dl></div>
            <legend id='148cP'><style id='148cP'><dir id='148cP'><q id='148cP'></q></dir></style></legend>
              <bdo id='148cP'></bdo><ul id='148cP'></ul>
                <tbody id='148cP'></tbody>

              <small id='148cP'></small><noframes id='148cP'>

                  本文介绍了如何使用 JSON.Net 转换新的日期(年、月、日)重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  限时送ChatGPT账号..

                  I'm trying to parse JSON file where dates are defined as JavaScript objects :

                  new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
                  

                  so I did try to parse it with the JavaScriptDateTimeConverter

                  test.json:

                  {"data" : [{"Date" : new Date(2015, 06, 01, 00, 00, 00)}]}
                  

                  c#:

                  using (StreamReader file = File.OpenText(@"c:	est.json"))
                  {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    Rootobject deserializedRoot = (Rootobject)serializer.Deserialize(file, typeof(Rootobject));
                  }
                  

                  Unfortunatly I'm receiving this error :

                  Unexpected token parsing date. Expected EndConstructor, got Integer. Path 'data[0].Date1', line 13, position 30.

                  From my understanding JSON.Net expect at best a new Date(52231943) but doesn't handle constructor overloads of Javascript Date() object.

                  Is there any known way to convert the new Date(year, month, day)?

                  解决方案

                  You could create your own subclass of JavaScriptDateTimeConverter.cs like so:

                  public class JavaScriptYMDDateTimeConverter : JavaScriptDateTimeConverter
                  {
                      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
                      {
                          Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
                          bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);
                  
                          var token = JToken.Load(reader);
                          if (token == null || token.Type == JTokenType.Null)
                          {
                              if (!isNullable)
                                  throw new JsonSerializationException(string.Format("Null value for type {0} at path {1}", objectType.Name, reader.Path));
                              return null;
                          }
                          if (token.Type != JTokenType.Constructor)
                          {
                              throw new JsonSerializationException(string.Format("Invalid Date constructor "{0}" at path {1}", token.ToString(), reader.Path));
                          }
                          var constructor = (JConstructor)token;
                          if (!string.Equals(constructor.Name, "Date", StringComparison.Ordinal))
                          {
                              throw new JsonSerializationException(string.Format("Invalid Date constructor "{0}" at path {1}", token.ToString(), reader.Path));
                          }
                  
                          var values = constructor.Values().ToArray();
                  
                          if (values.Length == 0)
                          {
                              throw new JsonSerializationException(string.Format("Invalid Date constructor "{0}" at path {1}", token.ToString(), reader.Path));
                          }
                          else if (values.Length == 1)
                          {
                              // Assume ticks
                              using (var subReader = constructor.CreateReader())
                              {
                                  while (subReader.TokenType != JsonToken.StartConstructor)
                                      subReader.Read();
                                  return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
                              }
                          }
                          else
                          {
                              var year = (values.Length > 0 ? (int)values[0] : 0);
                              var month = (values.Length > 1 ? (int)values[1] : 0) + 1; // c# months go from 1 to 12, JavaScript from 0 to 11
                              var day = (values.Length > 2 ? (int)values[2] : 0);
                              var hour = (values.Length > 3 ? (int)values[3] : 0);
                              var min = (values.Length > 4 ? (int)values[4] : 0);
                              var sec = (values.Length > 5 ? (int)values[5] : 0);
                              var ms = (values.Length > 6 ? (int)values[6] : 0);
                  
                              // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
                              // Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time.
                              var dt = new DateTime(year, month, day, hour, min, sec, ms, DateTimeKind.Local);
                              if (type == typeof(DateTimeOffset))
                                  return new DateTimeOffset(dt);
                              return dt;
                          }
                      }
                  }
                  

                  Here ReadJson() loads the token into a JConstructor, checks that the constructor name is Date, then parses the children.

                  Note I did not override WriteJson, so this converter will write in the same style as JavaScriptDateTimeConverter, with the ticks appearing as the single argument to the constructor.

                  Use it in place of JavaScriptDateTimeConverter().

                  这篇关于如何使用 JSON.Net 转换新的日期(年、月、日)重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
                  Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
                  Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
                  How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
                  how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
                  JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)
                    <i id='7FO74'><tr id='7FO74'><dt id='7FO74'><q id='7FO74'><span id='7FO74'><b id='7FO74'><form id='7FO74'><ins id='7FO74'></ins><ul id='7FO74'></ul><sub id='7FO74'></sub></form><legend id='7FO74'></legend><bdo id='7FO74'><pre id='7FO74'><center id='7FO74'></center></pre></bdo></b><th id='7FO74'></th></span></q></dt></tr></i><div id='7FO74'><tfoot id='7FO74'></tfoot><dl id='7FO74'><fieldset id='7FO74'></fieldset></dl></div>

                      <bdo id='7FO74'></bdo><ul id='7FO74'></ul>
                      • <tfoot id='7FO74'></tfoot>
                        • <legend id='7FO74'><style id='7FO74'><dir id='7FO74'><q id='7FO74'></q></dir></style></legend>
                              <tbody id='7FO74'></tbody>

                            <small id='7FO74'></small><noframes id='7FO74'>