當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。