当前位置: 首页>>代码示例>>C#>>正文


C# Linq.JTokenWriter类代码示例

本文整理汇总了C#中Newtonsoft.Json.Linq.JTokenWriter的典型用法代码示例。如果您正苦于以下问题:C# JTokenWriter类的具体用法?C# JTokenWriter怎么用?C# JTokenWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JTokenWriter类属于Newtonsoft.Json.Linq命名空间,在下文中一共展示了JTokenWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateJTokenDtoPartialPut

        public static JToken CreateJTokenDtoPartialPut(Byte[] key, Byte[] value, int valueLength, int valueOffset)
        {
            using (var jsonWriter = new JTokenWriter())
            {
                jsonWriter.WriteStartObject();

                if (key != null)
                {
                    jsonWriter.WritePropertyName("Key");
                    String base64 = Convert.ToBase64String(key, 0, key.Length);
                    jsonWriter.WriteValue(base64);
                }

                jsonWriter.WritePropertyName("Value");
                {
                    jsonWriter.WriteStartObject();

                    jsonWriter.WritePropertyName("Data");
                    String base64 = Convert.ToBase64String(value, valueOffset, valueLength);
                    jsonWriter.WriteValue(base64);

                    jsonWriter.WritePropertyName("Offset");
                    jsonWriter.WriteValue(valueOffset);

                    jsonWriter.WriteEndObject();
                }

                jsonWriter.WriteEndObject();
                return jsonWriter.Token;
            }
        }
开发者ID:voronov-maxim,项目名称:BerkeleyDb,代码行数:31,代码来源:SerializeHelper.cs

示例2: State

    public void State()
    {
      using (JsonWriter jsonWriter = new JTokenWriter())
      {
        Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);

        jsonWriter.WriteStartObject();
        Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

        jsonWriter.WritePropertyName("CPU");
        Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

        jsonWriter.WriteValue("Intel");
        Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

        jsonWriter.WritePropertyName("Drives");
        Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);

        jsonWriter.WriteStartArray();
        Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

        jsonWriter.WriteValue("DVD read/writer");
        Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

        jsonWriter.WriteValue(new byte[0]);
        Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);

        jsonWriter.WriteEnd();
        Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);

        jsonWriter.WriteEndObject();
        Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
      }
    }
开发者ID:adrianhewitt,项目名称:to-Screenshot-Generator,代码行数:34,代码来源:JTokenWriterTest.cs

示例3: CreateJTokenObject

        public static JToken CreateJTokenObject(BerkeleyDbError error, Byte[] key, Byte[] value, int keySize, int valueSize)
        {
            using (var jsonWriter = new JTokenWriter())
            {
                jsonWriter.WriteStartObject();

                if (error != 0)
                {
                    jsonWriter.WritePropertyName("ErrorCode");
                    jsonWriter.WriteValue((int)error);
                }

                if (key != null)
                {
                    jsonWriter.WritePropertyName("Key");
                    String base64 = Convert.ToBase64String(key, 0, keySize);
                    jsonWriter.WriteValue(base64);
                }

                if (value != null)
                {
                    jsonWriter.WritePropertyName("Value");
                    String base64 = Convert.ToBase64String(value, 0, valueSize);
                    jsonWriter.WriteValue(base64);
                }

                jsonWriter.WriteEndObject();
                return jsonWriter.Token;
            }
        }
开发者ID:voronov-maxim,项目名称:BerkeleyDb,代码行数:30,代码来源:ControllersHelper.cs

示例4: WriteJson

        public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
        {
            var jtw = new JTokenWriter();
            DefaultSerializer.Serialize( jtw, value );

            JToken token = jtw.Token;
            JObject obj = (JObject)token;
            JObject linksElement = new JObject();

            foreach( var prop in obj.Properties().ToList() )
            {
                if( IsPropertyActionLink( value.GetType(), prop.Name ) )
                {
                    //this property is an ActionLink, strip it from the root object and add to the "_links" element.
                    obj.Remove( prop.Name );
                    linksElement.Add( prop.Name, prop.Value );
                }
            }

            if( linksElement.Children().Count() > 0 )
            {
                obj.Add( LinksElementName, linksElement );
            }
            obj.WriteTo( writer, serializer.Converters.ToArray() );
        }
开发者ID:robzhu,项目名称:Library.WebApi,代码行数:25,代码来源:ResourceConverter.cs

示例5: Serialize

        public string Serialize(object value)
        {
            var writer = new JTokenWriter();
            var serializer = JsonSerializer.Create(settings);
            serializer.Serialize(writer, value);

            var container = writer.Token as JContainer;
            if (container != null)
            {
                var idProperties = container.Descendants().OfType<JProperty>().Where(d => d.Name == "$id").ToList();
                if (idProperties.Any())
                {
                    var refProperties = container.Descendants().OfType<JProperty>().Where(d => d.Name == "$ref").ToList();
                    if (refProperties.Any())
                    {
                        foreach (var idProperty in idProperties
                            .Where(idProperty => refProperties
                                .All(refProperty => refProperty.Value.ToString() != idProperty.Value.ToString())))
                        {
                            idProperty.Remove();
                        }
                    }
                    else
                    {
                        foreach (var idProperty in idProperties)
                        {
                            idProperty.Remove();
                        }
                    }
                }
            }

            return writer.Token.ToString();
        }
开发者ID:AsCloud,项目名称:scriptcs,代码行数:34,代码来源:ObjectSerializer.cs

示例6: Example

        public void Example()
        {
            #region Usage
            JTokenWriter writer = new JTokenWriter();
            writer.WriteStartObject();
            writer.WritePropertyName("name1");
            writer.WriteValue("value1");
            writer.WritePropertyName("name2");
            writer.WriteStartArray();
            writer.WriteValue(1);
            writer.WriteValue(2);
            writer.WriteEndArray();
            writer.WriteEndObject();

            JObject o = (JObject)writer.Token;

            Console.WriteLine(o.ToString());
            // {
            //   "name1": "value1",
            //   "name2": [
            //     1,
            //     2
            //   ]
            // }
            #endregion

            Assert.AreEqual(@"{
  ""name1"": ""value1"",
  ""name2"": [
    1,
    2
  ]
}", o.ToString());
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:34,代码来源:CreateJsonJTokenWriter.cs

示例7: ToGeoJson

        /// <summary>
        /// Generates GeoJson for the given feature collection.
        /// </summary>
        /// <param name="featureCollection"></param>
        public static string ToGeoJson(this FeatureCollection featureCollection)
        {
            if (featureCollection == null) { throw new ArgumentNullException("featureCollection"); }

            var jsonWriter = new JTokenWriter();
            GeoJsonConverter.Write(jsonWriter, featureCollection);
            return jsonWriter.Token.ToString();
        }
开发者ID:cmberryau,项目名称:core,代码行数:12,代码来源:GeoJsonConverter.cs

示例8: Invoke

 public virtual JToken Invoke(MethodInfo methodInfo, object instance, object[] parameters, JsonSerializer jsonSerializer)
 {
     object result = methodInfo.Invoke(instance, parameters);
     using(var writer = new JTokenWriter())
     {
         jsonSerializer.Serialize(writer, result);
         return writer.Token;
     }
 }
开发者ID:gimmi,项目名称:jsonrpchandler,代码行数:9,代码来源:MethodInvoker.cs

示例9: ReadJson

        /// <summary>
        /// 从字符流读取对象
        /// </summary>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            using (JTokenWriter writer = new JTokenWriter())
            {
                JsonReaderToJsonWriter(reader, writer);

                return writer.Token.ToObject(objectType);
            }
        }
开发者ID:269378737,项目名称:go81,代码行数:12,代码来源:CustomJsonConverter.cs

示例10: BuildViewModel

        /// <summary>
        /// Builds the view model for the client.
        /// </summary>
        public void BuildViewModel(DotvvmRequestContext context)
        {
            // serialize the ViewModel
            var serializer = CreateJsonSerializer();
            var viewModelConverter = new ViewModelJsonConverter(context.IsPostBack, viewModelMapper)
            {
                UsedSerializationMaps = new HashSet<ViewModelSerializationMap>()
            };
            serializer.Converters.Add(viewModelConverter);
            var writer = new JTokenWriter();
            try
            {
                serializer.Serialize(writer, context.ViewModel);
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not serialize viewModel of type { context.ViewModel.GetType().Name }. Serialization failed at property { writer.Path }. {GeneralViewModelRecomendations}", ex);
            }

            // persist CSRF token
            writer.Token["$csrfToken"] = context.CsrfToken;

            // persist encrypted values
            if (viewModelConverter.EncryptedValues.Count > 0)
                writer.Token["$encryptedValues"] = viewModelProtector.Protect(viewModelConverter.EncryptedValues.ToString(Formatting.None), context);

            // serialize validation rules
            var validationRules = SerializeValidationRules(viewModelConverter);

            // create result object
            var result = new JObject();
            result["viewModel"] = writer.Token;
            result["url"] = context.OwinContext.Request.Uri.PathAndQuery;
            result["virtualDirectory"] = DotvvmMiddleware.GetVirtualDirectory(context.OwinContext);
            if (context.ResultIdFragment != null)
            {
                result["resultIdFragment"] = context.ResultIdFragment;
            }
            if (context.IsPostBack || context.IsSpaRequest)
            {
                result["action"] = "successfulCommand";
                var renderedResources = new HashSet<string>(context.ReceivedViewModelJson?["renderedResources"]?.Values<string>() ?? new string[] { });
                result["resources"] = BuildResourcesJson(context, rn => !renderedResources.Contains(rn));
            }
            else
            {
                result["renderedResources"] = JArray.FromObject(context.ResourceManager.RequiredResources);
            }
            // TODO: do not send on postbacks
            if (validationRules.Count > 0) result["validationRules"] = validationRules;

            context.ViewModelJson = result;
        }
开发者ID:darilek,项目名称:dotvvm,代码行数:56,代码来源:DefaultViewModelSerializer.cs

示例11: BuildViewModel

        /// <summary>
        /// Builds the view model for the client.
        /// </summary>
        public void BuildViewModel(DotvvmRequestContext context, DotvvmView view)
        {
            // serialize the ViewModel
            var serializer = CreateJsonSerializer();
            var viewModelConverter = new ViewModelJsonConverter()
            {
                EncryptedValues = new JArray(),
                UsedSerializationMaps = new HashSet<ViewModelSerializationMap>()
            };
            serializer.Converters.Add(viewModelConverter);
            var writer = new JTokenWriter();
            serializer.Serialize(writer, context.ViewModel);

            // persist CSRF token
            writer.Token["$csrfToken"] = context.CsrfToken;

            // persist encrypted values
            if (viewModelConverter.EncryptedValues.Count > 0)
                writer.Token["$encryptedValues"] = viewModelProtector.Protect(viewModelConverter.EncryptedValues.ToString(Formatting.None), context);

            // serialize validation rules
            var validationRules = SerializeValidationRules(viewModelConverter);

            // create result object
            var result = new JObject();
            result["viewModel"] = writer.Token;
            result["url"] = context.OwinContext.Request.Uri.PathAndQuery;
            result["virtualDirectory"] = DotvvmMiddleware.GetVirtualDirectory(context.OwinContext);
            if (context.IsPostBack || context.IsSpaRequest)
            {
                result["action"] = "successfulCommand";
                var renderedResources = new HashSet<string>(context.ReceivedViewModelJson?["renderedResources"]?.Values<string>() ?? new string[] { });
                result["resources"] = BuildResourcesJson(context, rn => !renderedResources.Contains(rn));
            }
            else
            {
                result["renderedResources"] = JArray.FromObject(context.ResourceManager.RequiredResources);
            }
            // TODO: do not send on postbacks
            if (validationRules.Count > 0) result["validationRules"] = validationRules;

            context.ViewModelJson = result;
        }
开发者ID:holajan,项目名称:dotvvm,代码行数:46,代码来源:DefaultViewModelSerializer.cs

示例12: ValueFormatting

        public void ValueFormatting()
        {
            byte[] data = Encoding.UTF8.GetBytes("Hello world.");

            JToken root;
            using (JTokenWriter jsonWriter = new JTokenWriter())
            {
                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((string)null);
                jsonWriter.WriteValue("This is a string.");
                jsonWriter.WriteNull();
                jsonWriter.WriteUndefined();
                jsonWriter.WriteValue(data);
                jsonWriter.WriteEndArray();

                root = jsonWriter.Token;
            }

            CustomAssert.IsInstanceOfType(typeof(JArray), root);
            Assert.AreEqual(13, root.Children().Count());
            Assert.AreEqual("@", (string)root[0]);
            Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
            Assert.AreEqual(true, (bool)root[2]);
            Assert.AreEqual(10, (int)root[3]);
            Assert.AreEqual(10.99, (double)root[4]);
            Assert.AreEqual(0.99, (double)root[5]);
            Assert.AreEqual(0.000000000000000001d, (double)root[6]);
            Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
            Assert.AreEqual(null, (string)root[8]);
            Assert.AreEqual("This is a string.", (string)root[9]);
            Assert.AreEqual(null, ((JValue)root[10]).Value);
            Assert.AreEqual(null, ((JValue)root[11]).Value);
            Assert.AreEqual(data, (byte[])root[12]);
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:42,代码来源:JTokenWriterTest.cs

示例13: SerializeObject

        public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
        {
            var settings = new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.None,
                TypeNameHandling = TypeNameHandling.Objects,
                ContractResolver = new EdContractResolver(),
                Binder = new EdSerializationBinder(),
                Converters = converters
            };
            var serializer = JsonSerializer.Create(settings);
            using (var writer = new JTokenWriter())
            {
                serializer.Serialize(writer, value);
                var root = (JObject)writer.Token;
                root = GraphRewriter.Deconstruct(root);

                return root.ToString(formatting);
            }
        }
开发者ID:rmichela,项目名称:EmberDataAdapter,代码行数:20,代码来源:EmberDataJsonConvert.cs

示例14: JTokenWriter

    public void JTokenWriter()
    {
      JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
      ignoreAttributeOnClassTestClass.Field = int.MinValue;

      JsonSerializer serializer = new JsonSerializer();
      serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();

      JTokenWriter writer = new JTokenWriter();

      serializer.Serialize(writer, ignoreAttributeOnClassTestClass);

      JObject o = (JObject) writer.Token;
      JProperty p = o.Property("theField");

      Assert.IsNotNull(p);
      Assert.AreEqual(int.MinValue, (int)p.Value);

      string json = o.ToString();
    }
开发者ID:thirumg,项目名称:Avro.NET,代码行数:20,代码来源:CamelCasePropertyNamesContractResolverTests.cs

示例15: Example

    public void Example()
    {
      JTokenWriter writer = new JTokenWriter();
      writer.WriteStartObject();
      writer.WritePropertyName("name1");
      writer.WriteValue("value1");
      writer.WritePropertyName("name2");
      writer.WriteStartArray();
      writer.WriteValue(1);
      writer.WriteValue(2);
      writer.WriteEndArray();
      writer.WriteEndObject();

      JObject o = (JObject)writer.Token;

      Console.WriteLine(o.ToString());
      // {
      //   "name1": "value1",
      //   "name2": [
      //     1,
      //     2
      //   ]
      // }
    }
开发者ID:che3tah7,项目名称:Newtonsoft.Json,代码行数:24,代码来源:CreateJsonJTokenWriter.cs


注:本文中的Newtonsoft.Json.Linq.JTokenWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。