/// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                CheckedRead(reader);
            }

            if (reader.TokenType != JsonToken.StartArray)
                throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

            CheckedRead(reader);

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                CheckedRead(reader);
            }

            return dt;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            NameContainer nameContainer = new NameContainer();
            nameContainer.Value = (string)reader.Value;

            return nameContainer;
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                reader.Read();
            }

            if (reader.TokenType == JsonToken.StartArray)
                reader.Read();

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                reader.Read();
            }

            return dt;
        }
Example #4
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WritePropertyName("coordinates");

            List<List<Coordinate[]>> coordinatesss = value as List<List<Coordinate[]>>;
            if (coordinatesss != null)
            {
                WriteJsonCoordinatesEnumerable2(writer, coordinatesss, serializer);
                return;
            }

            List<Coordinate[]> coordinatess = value as List<Coordinate[]>;
            if (coordinatess != null)
            {
                WriteJsonCoordinatesEnumerable(writer, coordinatess, serializer);
                return;
            }

            IEnumerable<Coordinate> coordinates = value as IEnumerable<Coordinate>;
            if (coordinates != null)
            {
                WriteJsonCoordinates(writer, coordinates, serializer);
                return;
            }

            Coordinate coordinate = value as Coordinate;
            if (coordinate != null)
            {
                WriteJsonCoordinate(writer, coordinate, serializer);
                return;
            }
        }
 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         return null;
     }
     else
     {
         if (reader.TokenType == JsonToken.String)
         {
             try
             {
                 Version v = new Version((string)reader.Value);
                 return v;
             }
             catch (Exception ex)
             {
                 throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
             }
         }
         else
         {
             throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
     }
 }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            Enum e = (Enum)value;

            string enumName = e.ToString("G");

            if (char.IsNumber(enumName[0]) || enumName[0] == '-')
            {
                // enum value has no name so write number
                writer.WriteValue(value);
            }
            else
            {
                Type enumType = e.GetType();

                string finalName = EnumUtils.ToEnumName(enumType, enumName, CamelCaseText);

                writer.WriteValue(finalName);
            }
        }
Example #7
0
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      if (value == null)
      {
        writer.WriteNull();
        return;
      }

      Enum e = (Enum)value;

      string enumName = e.ToString("G");

      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
      {
        writer.WriteValue(value);
      }
      else
      {
        BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());

        string resolvedEnumName;
        map.TryGetByFirst(enumName, out resolvedEnumName);
        resolvedEnumName = resolvedEnumName ?? enumName;

        if (CamelCaseText)
        {
          string[] names = resolvedEnumName.Split(',').Select(item => StringUtils.ToCamelCase(item.Trim())).ToArray();
          resolvedEnumName = string.Join(", ", names);
        }

        writer.WriteValue(resolvedEnumName);
      }
    }
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			// NOTE: THIS DOESN'T SUPPORT READING OF DynamicJsonObject !!!

			var o = RavenJToken.Load(reader);
			return (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined) ? null : o;
		}
        public void testJsonDeserializingAnalyticServiceStatus()
        {
            String source =
                    "{" +
                        "\"service_status\":\"online\"," +
                        "\"api_version\":\"2.0\"," +
                        "\"service_version\":\"1.0.2.63\"," +
                        "\"supported_encoding\":\"UTF-8\"," +
                        "\"supported_compression\":\"gzip\"," +
                        "\"supported_languages\":[" +
                                "\"English\"," +
                                "\"French\"" +
                        "]" +
                    "}";

            ISerializer serializer = new JsonSerializer();
            Status status = serializer.Deserialize<Status>(source);
            Assert.AreEqual("online", status.Service);
            Assert.AreEqual("2.0", status.ApiVersion);
            Assert.AreEqual("1.0.2.63", status.ServiceVersion);
            Assert.AreEqual("UTF-8", status.SupportedEncoding);
            Assert.AreEqual("gzip", status.SupportedCompression);
            Assert.AreEqual(2, status.SupportedLanguages.Count);
            Assert.AreEqual("English", status.SupportedLanguages[0]);
            Assert.AreEqual("French", status.SupportedLanguages[1]);
        }
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                User user = new User();
                user.UserName = (string)reader.Value;

                return user;
            }
        public DatabaseSettingsSectionViewModel()
        {
            serializer = ApplicationModel.Current.Server.Value.DocumentStore.Conventions.CreateSerializer();
            serializer.Formatting = Formatting.Indented;

            SectionName = "Database Settings";
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if(value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((value as UniquenessType?).HasValue)
                writer.WriteValue(enumToStrings[typeof(UniquenessType?)](value));

            else if ((value as TraversalStrategy?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalStrategy?)](value));

            else if ((value as TraversalOrder?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalOrder?)](value));

            else if ((value as TraversalItemOrder?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalItemOrder?)](value));

            else if ((value as EdgeDirection?).HasValue)
                writer.WriteValue(enumToStrings[typeof(EdgeDirection?)](value));

            else
                throw new InvalidOperationException($"cant find binding to serialize type {value.GetType()}, this is client bug");
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var converter = GetConverter(value.GetType());
            var text = converter.ConvertToInvariantString(value);

            writer.WriteValue(text);
        }
        public JsonSerializerProxy(JsonSerializerWriter serializerWriter)
        {
            ValidationUtils.ArgumentNotNull(serializerWriter, "serializerWriter");

              _serializerWriter = serializerWriter;
              _serializer = serializerWriter._serializer;
        }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
      //long ticks;

      /*if (value is DateTime) {
        DateTime dateTime = (DateTime)value;
        DateTime utcDateTime = dateTime.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTime);
      } else if (value is DateTimeOffset) {
        DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
        DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
      } else {
        throw new Exception("Expected date object value.");
      }*/

      //writer.WriteStartConstructor("Date");
      //writer.WriteValue(ticks);
      //writer.WriteEndConstructor();
      if (value is DateTime) {
        DateTime dateTime = (DateTime)value;
        DateTime vLocValue = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
        writer.WriteValue(vLocValue);
      } else {
        throw new Exception("Expected date object value.");
      }
    }
Example #16
0
 public MapReduceIndex(Directory directory, int id, IndexDefinition indexDefinition,
                       AbstractViewGenerator viewGenerator, WorkContext context)
     : base(directory, id, indexDefinition, viewGenerator, context)
 {
     jsonSerializer = JsonExtensions.CreateDefaultJsonSerializer();
     jsonSerializer.Converters = MapReduceConverters;
 }
 // Token: 0x06000685 RID: 1669
 // RVA: 0x0003758C File Offset: 0x0003578C
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullable(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", CultureInfo.InvariantCulture, objectType));
         }
         return null;
     }
     else
     {
         if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token or value when parsing date. Token: {0}, Value: {1}", CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
         reader.Read();
         if (reader.TokenType != JsonToken.Integer)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected Integer, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         long javaScriptTicks = (long)reader.Value;
         DateTime dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
         reader.Read();
         if (reader.TokenType != JsonToken.EndConstructor)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected EndConstructor, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         return dateTime;
     }
 }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      if (value == null)
      {
        writer.WriteNull();
        return;
      }

      Enum e = (Enum)value;

      string enumName = e.ToString("G");

      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
      {
        writer.WriteValue(value);
      }
      else
      {
        BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());

        string resolvedEnumName;
        map.TryGetByFirst(enumName, out resolvedEnumName);
        resolvedEnumName = resolvedEnumName ?? enumName;

		if (CamelCaseText)
          resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName);

        writer.WriteValue(resolvedEnumName);
      }
    }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DataTable table = (DataTable)value;
            DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;

            writer.WriteStartArray();

            foreach (DataRow row in table.Rows)
            {
                writer.WriteStartObject();
                foreach (DataColumn column in row.Table.Columns)
                {
                    object columnValue = row[column];

                    if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value))
                    {
                        continue;
                    }

                    writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
                    serializer.Serialize(writer, columnValue);
                }
                writer.WriteEndObject();
            }

            writer.WriteEndArray();
        }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
      Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;

      writer.WriteStartObject();
      writer.WritePropertyName("Key");
      writer.WriteValue(entityKeyMember.Key);
      writer.WritePropertyName("Type");
      writer.WriteValue((keyType != null) ? keyType.FullName : null);

      writer.WritePropertyName("Value");

      if (keyType != null)
      {
        string valueJson;
        if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
          writer.WriteValue(valueJson);
        else
          writer.WriteValue(entityKeyMember.Value);
      }
      else
      {
        writer.WriteNull();
      }

      writer.WriteEndObject();
    }
Example #21
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            reader.Read();

            Debug.Assert(reader.TokenType == JsonToken.PropertyName);
            Debug.Assert((string)reader.Value == "coordinates");

            if (objectType == typeof(Coordinate))
            {
                return ReadJsonCoordinate(reader);
            }

            if (typeof(IEnumerable<Coordinate>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinates(reader);
            }

            if (typeof(List<Coordinate[]>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable(reader);
            }
            if (typeof(List<List<Coordinate[]>>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable2(reader);
            }

            throw new Exception();
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // handle typed datasets
            DataSet ds = (objectType == typeof(DataSet))
                ? new DataSet()
                : (DataSet)Activator.CreateInstance(objectType);

            DataTableConverter converter = new DataTableConverter();

            reader.Read();

            while (reader.TokenType == JsonToken.PropertyName)
            {
                DataTable dt = ds.Tables[(string)reader.Value];
                bool exists = (dt != null);

                dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer);

                if (!exists)
                    ds.Tables.Add(dt);

                reader.Read();
            }

            return ds;
        }
Example #23
0
    public void EntitiesTest()
    {
      Purchase purchase = new Purchase() { Id = 1 };
      purchase.PurchaseLine.Add(new PurchaseLine() { Id = 1, Purchase = purchase });
      purchase.PurchaseLine.Add(new PurchaseLine() { Id = 2, Purchase = purchase });

      StringWriter sw = new StringWriter();
      JsonSerializer serializer = new JsonSerializer();
      serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

      using (JsonWriter jw = new JsonTextWriter(sw))
      {
        jw.Formatting = Formatting.Indented;

        serializer.Serialize(jw, purchase);
      }

      string json = sw.ToString();

      Assert.AreEqual(@"{
  ""Id"": 1,
  ""PurchaseLine"": [
    {
      ""Id"": 1,
      ""PurchaseReference"": {
        ""EntityKey"": null,
        ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"",
        ""SourceRoleName"": ""PurchaseLine"",
        ""TargetRoleName"": ""Purchase"",
        ""RelationshipSet"": null,
        ""IsLoaded"": false
      },
      ""EntityState"": 1,
      ""EntityKey"": null
    },
    {
      ""Id"": 2,
      ""PurchaseReference"": {
        ""EntityKey"": null,
        ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"",
        ""SourceRoleName"": ""PurchaseLine"",
        ""TargetRoleName"": ""Purchase"",
        ""RelationshipSet"": null,
        ""IsLoaded"": false
      },
      ""EntityState"": 1,
      ""EntityKey"": null
    }
  ],
  ""EntityState"": 1,
  ""EntityKey"": null
}", json);

      Purchase newPurchase = JsonConvert.DeserializeObject<Purchase>(json);
      Assert.AreEqual(1, newPurchase.Id);

      Assert.AreEqual(2, newPurchase.PurchaseLine.Count);
      Assert.AreEqual(1, newPurchase.PurchaseLine.ElementAt(0).Id);
      Assert.AreEqual(2, newPurchase.PurchaseLine.ElementAt(1).Id);
    }
Example #24
0
        public void Date()
        {
            var serializer = new JsonSerializer();
            DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            Action<DateTime, string> CheckDate = (date, json) => {
                var result = serializer.Deserialize<DateTime>(json);
                var diff = date.Subtract(result);
                Assert.IsTrue(diff.TotalSeconds < 1, string.Format("Dates do not match: <{0}> != <{1}>, difference: {2}, json: <{3}>", date, result, diff.TotalSeconds, json));
            };

            Action<DateTime> TestDate = (source) => {
                CheckDate(source, string.Format("new Date({0})", (long)(source - EPOCH).TotalMilliseconds));
                CheckDate(source, string.Format("new Date(\"{0}\")", source.ToString("MMMM d, yyyy HH:mm:ss zzz")));
                CheckDate(source, string.Format("new Date({0}, {1}, {2}, {3}, {4}, {5}, {6})", source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond));
            };

            TestDate(new DateTime(1970, 1, 2, 0, 0, 0, DateTimeKind.Utc));
            TestDate(new DateTime(1970, 1, 2, 4, 0, 0, DateTimeKind.Utc));
            TestDate(new DateTime(1970, 1, 2, 14, 0, 0, DateTimeKind.Utc));
            TestDate(DateTime.Now);
            TestDate(DateTime.UtcNow);

            CheckDate(new DateTime(1970, 1, 2, 4, 1, 2), "new Date(1970, 1, 2, 14, 0, 0)");
            CheckDate(new DateTime(1970, 1, 2, 4, 1, 0), "new Date(1970, 1, 2, 14, 0)");
            CheckDate(new DateTime(1970, 1, 2, 4, 0, 0), "new Date(1970, 1, 2, 14)");
            CheckDate(new DateTime(1970, 1, 2, 0, 0, 0), "new Date(1970, 1, 2)");
        }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            EnsureReflectionObject(value.GetType());

            DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;

            string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName);
            object keyValue = _reflectionObject.GetValue(value, ValuePropertyName);

            Type keyValueType = (keyValue != null) ? keyValue.GetType() : null;

            writer.WriteStartObject();
            writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
            writer.WriteValue(keyName);
            writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName);
            writer.WriteValue((keyValueType != null) ? keyValueType.FullName : null);

            writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName);

            if (keyValueType != null)
            {
                string valueJson;
                if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out valueJson))
                    writer.WriteValue(valueJson);
                else
                    writer.WriteValue(keyValue);
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
 private static void WriteJsonCoordinates(JsonWriter writer, IEnumerable<Coordinate> coordinates, JsonSerializer serializer)
 {
     writer.WriteStartArray();
     foreach (Coordinate coordinate in coordinates)
         WriteJsonCoordinate(writer, coordinate, serializer);
     writer.WriteEndArray();
 }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      long ticks;

      if (value is DateTime)
      {
        DateTime dateTime = (DateTime)value;
        DateTime utcDateTime = dateTime.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTime);
      }
#if !PocketPC && !NET20
      else if (value is DateTimeOffset)
      {
        DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
        DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
      }
#endif
      else
      {
        throw new JsonSerializationException("Expected date object value.");
      }

      writer.WriteStartConstructor("Date");
      writer.WriteValue(ticks);
      writer.WriteEndConstructor();
    }
 private static void WriteJsonCoordinatesEnumerable2(JsonWriter writer, List<List<Coordinate[]>> coordinates, JsonSerializer serializer)
 {
     writer.WriteStartArray();
     foreach (List<Coordinate[]> coordinate in coordinates)
         WriteJsonCoordinatesEnumerable(writer, coordinate, serializer);
     writer.WriteEndArray();
 }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;

                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    dateTime = dateTime.ToUniversalTime();

                text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#if !NET20
            else if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();

                text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#endif
            else
            {
                throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
            }

            writer.WriteValue(text);
        }
Example #30
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.webHybrid = new WebHybrid(this.webView, new JsonSerializer());

            SaveFilesInHTMLFolderToIsoStore();
            this.webView.Navigate(new Uri("HTML/home.html", UriKind.Relative));

            //var fi = new FileInfo(@"./Assets/home.html");

            //using (var streamReader = new StreamReader(fi.FullName))
            //{
            //    this.webView.NavigateToString(streamReader.ReadToEnd());
            //}

            this.webHybrid.RegisterCallback("test", s =>
                {
                    System.Diagnostics.Debug.WriteLine(s);
                    var serializer = new JsonSerializer();
                    var m = serializer.Deserialize<ChartViewModel>(s);
                    System.Diagnostics.Debug.WriteLine(m);
                });

            this.webHybrid.RegisterCallback("dataCallback", s => System.Diagnostics.Debug.WriteLine(s));
        }