internal static void ExportTable(DataTable table, JsonWriter writer)
        {
            Debug.Assert(table != null);
            Debug.Assert(writer != null);

            DataViewExporter.ExportView(table.DefaultView, writer);
       }
        /// <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();
        }
    /// <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();
    }
        /// <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 #5
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);
      }
    }
Example #6
0
 public void WritesNonEscapedString()
 {
     var sw = new StringWriter();
     var writer = new JsonWriter(sw);
     writer.WriteValue("hello, world");
     Assert.AreEqual("\"hello, world\"", sw.ToString());
 }
Example #7
0
 public void WritesEscapedControlCharacters()
 {
     var sw = new StringWriter();
     var writer = new JsonWriter(sw);
     writer.WriteValue("this is escaped: \b\f\n\r\t\x17");
     Assert.AreEqual("\"this is escaped: \\b\\f\\n\\r\\t\\x17\"", sw.ToString());
 }
Example #8
0
    public void ValueFormatting()
    {
      StringBuilder sb = new StringBuilder();
      StringWriter sw = new StringWriter(sb);

      using (JsonWriter jsonWriter = new JsonWriter(sw))
      {
        jsonWriter.WriteStartArray();
        jsonWriter.WriteValue('@');
        jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
        jsonWriter.WriteValue(true);
        jsonWriter.WriteValue(10);
        jsonWriter.WriteValue(10.99);
        jsonWriter.WriteValue(0.99);
        jsonWriter.WriteValue(0.000000000000000001d);
        jsonWriter.WriteValue(0.000000000000000001m);
        jsonWriter.WriteValue(null);
        jsonWriter.WriteValue("This is a string.");
        jsonWriter.WriteNull();
        jsonWriter.WriteUndefined();
        jsonWriter.WriteEndArray();
      }

      const string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,,""This is a string."",null,undefined]";
      string result = sb.ToString();

      Console.WriteLine("ValueFormatting");
      Console.WriteLine(result);

      Assert.AreEqual(expected, result);
    }
Example #9
0
    void WriteResponseForPostJson(HttpRequest request, HttpResponse response)
    {
        // read request JSON
        uint requestedCount = ReadCount(request.Body);

        // write response JSON
        var json = new JsonWriter<ResponseFormatter>(response.Body, prettyPrint: false);
        json.WriteObjectStart();
        json.WriteArrayStart();
        for (int i = 0; i < requestedCount; i++) {
            json.WriteString("hello!"); 
        }
        json.WriteArrayEnd();
        json.WriteObjectEnd();

        // write headers
        var headers = response.Headers;
        headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
        headers.Append("Content-Length : ");
        headers.Append(response.Body.CommitedBytes);
        headers.AppendHttpNewLine();
        headers.Append("Content-Type : text/plain; charset=UTF-8");
        headers.AppendHttpNewLine();
        headers.Append("Server : .NET Core Sample Server");
        headers.AppendHttpNewLine();
        headers.Append("Date : ");
        headers.Append(DateTime.UtcNow, 'R');
        headers.AppendHttpNewLine();
        headers.AppendHttpNewLine();
    }
    public override void WriteJson(JsonWriter writer, object value)
    {
      DateTime dateTime = (DateTime)value;
      long javaScriptTicks = JavaScriptConvert.ConvertDateTimeToJavaScriptTicks(dateTime);

      writer.WriteValue("@" + javaScriptTicks.ToString(null, CultureInfo.InvariantCulture) + "@");
    }
		/// <summary>
		/// Write this target to a JsonWriter
		/// </summary>
		/// <param name="Writer">Writer to output to</param>
		void Write(JsonWriter Writer)
		{
			Writer.WriteObjectStart();
			Writer.WriteValue("Name", Name);
			Writer.WriteValue("LoadingPolicy", LoadingPolicy.ToString());
			Writer.WriteObjectEnd();
		}
Example #12
0
 protected override void ExportValue(ExportContext context, object value, JsonWriter writer)
 {
     Debug.Assert(value != null);
     Debug.Assert(writer != null);
     
     ExportTime((DateTime) value, writer);
 }
Example #13
0
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dataResult = value as DataResult;

            #region 序列化DataResult对象

            writer.WriteStartObject();
            // 写total属性
            writer.WritePropertyName("total");
            serializer.Serialize(writer, dataResult.Total);
            // 写pagecount属性
            writer.WritePropertyName("pagecount");
            serializer.Serialize(writer, dataResult.PageCount);
            // 写pageindex属性
            writer.WritePropertyName("pageindex");
            serializer.Serialize(writer, dataResult.PageIndex);

            // 写rows属性
            var converter = new DataTableConverter();
            writer.WritePropertyName("rows");
            converter.WriteJson(writer, dataResult.Data, serializer);
            writer.WriteEndObject();

            #endregion
    }
        protected override void ExportValue(ExportContext context, object value, JsonWriter writer)
        {
            Debug.Assert(context != null);
            Debug.Assert(value != null);
            Debug.Assert(writer != null);
            
            if (_properties.Count == 0)
            {
                writer.WriteString(value.ToString());
            }
            else
            {
                writer.WriteStartObject();

                foreach (PropertyDescriptor property in _properties)
                {
                    object propertyValue = property.GetValue(value);
                
                    if (!JsonNull.LogicallyEquals(propertyValue))
                    {
                        writer.WriteMember(property.Name);
                        context.Export(propertyValue, writer);
                    }
                }

                writer.WriteEndObject();
            }
        }
Example #15
0
 public void WriteToService()
 {
     System.Text.StringBuilder m_write = new System.Text.StringBuilder();
     JsonWriter m_writer = new JsonWriter(m_write);
     m_writer.WriteObjectStart();
     m_writer.WritePropertyName("ButtonID");
 }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is string)
            {
                if (Value_RE.Match(value.ToString()).Success) 
                {
                    writer.WriteRawValue(value.ToString()); 
                }
                else
                {
                    string prms;
                    
                    switch (this.Name)
                    {
                        case "before":
                            prms = "el,type,action,extraParams,o";
                            break;
                        case "complete":
                            prms = "success,response,result,el,type,action,extraParams,o";
                            break;
                        default:
                            prms = "response,result,el,type,action,extraParams,o";
                            break;
                    }

                    value = TokenUtils.ReplaceRawToken(TokenUtils.ParseTokens(value.ToString(), this.OwnerControl));
                    writer.WriteRawValue(new JFunction((string)value, prms).ToScript()); 
                }
            }
        }
    /// <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.");
      }
    }
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     if (value is string[])
     {
         writer.WriteRawValue("[{0}]".FormatWith(((string[])value).Join(",", "\"{0}\"")));
     }
 }
Example #19
0
 public void WritesEscapedQuoteString()
 {
     var sw = new StringWriter();
     var writer = new JsonWriter(sw);
     writer.WriteValue("this is escaped: \"");
     Assert.AreEqual("\"this is escaped: \\\"\"", sw.ToString());
 }
Example #20
0
 public void WritesByte()
 {
     var sw = new StringWriter();
     var writer = new JsonWriter(sw);
     writer.WriteValue((Byte)123);
     Assert.AreEqual("123", sw.ToString());
 }
Example #21
0
 public void WritesEscapedUnicodeCharacters()
 {
     var sw = new StringWriter();
     var writer = new JsonWriter(sw);
     writer.WriteValue("this is escaped: \u3034");
     Assert.AreEqual("\"this is escaped: \\u3034\"", sw.ToString());
 }
        public void JsonWriter_EscapeCharacters()
        {
            var body = new Dictionary<string, object>();
            body.Add("b", "\b");
            body.Add("t", "\t");
            body.Add("n", "\n");
            body.Add("f", "\f");
            body.Add("r", "\r");
            body.Add("q", "\"");
            body.Add("rs", "\\");
            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                var jw = new JsonWriter(sw);
                jw.WriteValue(body);
                sw.Flush();
            }

            Assert.AreEqual("{" +
                @"""b"":""\u0008""," +
                @"""t"":""\u0009""," +
                @"""n"":""\u000a""," +
                @"""f"":""\u000c""," +
                @"""r"":""\u000d""," +
                @"""q"":""\""""," +
                @"""rs"":""\\""" + "}",
                sb.ToString());
        }
        /// <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();
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var converter = GetConverter(value.GetType());
            var text = converter.ConvertToInvariantString(value);

            writer.WriteValue(text);
        }
    private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
    {
      if (contract.UnderlyingType == typeof (byte[]))
      {
        bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
        if (includeTypeDetails)
        {
          writer.WriteStartObject();
          WriteTypeProperty(writer, contract.CreatedType);
          writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);

          if (contract.IsNullable)
            writer.WriteValue(value, true);
          else
            writer.WriteValue(value);

          writer.WriteEndObject();
          return;
        }
      }

      if (contract.IsNullable)
        writer.WriteValue(value, true);
      else
        writer.WriteValue(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] == '-')
      {
        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);
      }
    }
    public void Serialize(JsonWriter jsonWriter, object value)
    {
      if (jsonWriter == null)
        throw new ArgumentNullException("jsonWriter");

      SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
    }
    /// <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();
    }
        /// <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);
        }
        protected override void ExportValue(object value, JsonWriter writer)
        {
            Debug.Assert(value != null);
            Debug.Assert(writer != null);

            ExportTable((DataTable) value, writer);
        }