コード例 #1
0
        public void CurrentToken()
        {
            using (JTokenWriter jsonWriter = new JTokenWriter())
            {
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
                Assert.AreEqual(null, jsonWriter.CurrentToken);

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

                JObject o = (JObject)jsonWriter.Token;

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

                jsonWriter.WriteValue("Intel");
                Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
                Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken);

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

                jsonWriter.WriteStartArray();
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
                Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken);

                JArray a = (JArray)jsonWriter.CurrentToken;

                jsonWriter.WriteValue("DVD read/writer");
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
                Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);

#if !(NET20 || NET35 || PORTABLE || DNXCORE50 || PORTABLE40)
                jsonWriter.WriteValue(new BigInteger(123));
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
                Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#endif

                jsonWriter.WriteValue(new byte[0]);
                Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
                Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);

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

                jsonWriter.WriteEndObject();
                Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
                Assert.AreEqual(o, jsonWriter.CurrentToken);
            }
        }
コード例 #2
0
        public void WriteComment()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteComment("fail");
            writer.WriteEndArray();

            StringAssert.AreEqual(@"[
  /*fail*/]", writer.Token.ToString());
        }
コード例 #3
0
        public void WriteFullDecimalPrecision()
        {
            var jTokenWriter = new JTokenWriter();

            new JsonSerializer().Serialize(jTokenWriter, rate);
            string json = jTokenWriter.Token.ToString();

            Assert.AreEqual(@"{
  ""Compoundings"": 12.166666666666666666666666667
}", json);
        }
コード例 #4
0
ファイル: JValueTests.cs プロジェクト: belav/Newtonsoft.Json
        public void RoundTripDecimal()
        {
            var jTokenWriter = new JTokenWriter();

            new JsonSerializer().Serialize(jTokenWriter, rate);
            var rate2 = new JsonSerializer().Deserialize <Rate>(
                new JTokenReader(jTokenWriter.Token)
                );

            Assert.AreEqual(rate.Compoundings, rate2.Compoundings);
        }
コード例 #5
0
        /// <summary>
        /// Gets the client-side data as a <see cref="JToken"/>
        /// </summary>
        /// <returns></returns>
        JToken CreateNodeJObject(Document document)
        {
            Contract.Requires <ArgumentNullException>(document != null);

            // serialize document state to data field
            using (var wrt = new JTokenWriter())
            {
                RemoteHelper.GetJson(wrt, document.Root);
                return(wrt.Token);
            }
        }
コード例 #6
0
        public void SendJoinToGame(string token)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("game_token");
            writer.WriteValue(token);
            writer.WritePropertyName("user_name");
            writer.WriteValue(context.gameCtrl.UserName);
            writer.WriteEndObject();
            SendJsonData("POST", "/join_game", null, writer.Token.ToString());
        }
コード例 #7
0
ファイル: JsonFilter.cs プロジェクト: ejball/FaithlifeJson
        /// <summary>
        /// Filters data from the specified object.
        /// </summary>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <param name="value">The object instance.</param>
        /// <param name="settings">The settings used when reading/writing JSON.</param>
        /// <returns>A new object with the specified data filtered.</returns>
        /// <remarks>This method converts the object to JSON, filtering out data as
        /// appropriate, and then converts the filtered JSON back into an object.</remarks>
        public T FilterObject <T>(T value, JsonSettings settings)
        {
            if (value == null)
            {
                return(default(T));
            }

            var tokenWriter = new JTokenWriter();

            JsonUtility.ToJsonWriter(value, settings, CreateFilteredJsonWriter(tokenWriter));
            return(JsonUtility.FromJToken <T>(tokenWriter.Token, settings));
        }
コード例 #8
0
        public void Can_Serialize_Int32OrStringV1_Null(object rawValue, object renderedValue)
        {
            Int32OrStringV1 int32OrString;

            if (rawValue is string stringValue)
            {
                int32OrString = stringValue;
            }
            else if (rawValue is int intValue)
            {
                int32OrString = intValue;
            }
            else if (rawValue == null)
            {
                int32OrString = null;
            }
            else
            {
                throw new InvalidOperationException($"Unexpected value type: '{rawValue.GetType().FullName}'.");
            }

            var model = new TestModel
            {
                Number = 123,
                Text   = "hello",
                Mixed  = int32OrString
            };

            JObject rootObject;

            using (JTokenWriter writer = new JTokenWriter())
            {
                JsonSerializer
                .Create(new JsonSerializerSettings
                {
                    Converters =
                    {
                        new Int32OrStringV1Converter()
                    }
                })
                .Serialize(writer, model);

                writer.Flush();

                rootObject = (JObject)writer.Token;
            }

            string propertyName  = GetJsonPropertyName(typeof(TestModel), "Mixed");
            var    propertyValue = rootObject.Property(propertyName)?.Value as JValue;

            Assert.NotNull(propertyValue);
            Assert.Equal(renderedValue, propertyValue.Value);
        }
コード例 #9
0
        /// <summary>
        /// Generates GeoJson for this geometry.
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        public static string ToGeoJson(this Point geometry)
        {
            if (geometry == null)
            {
                throw new ArgumentNullException("geometry");
            }

            var jsonWriter = new JTokenWriter();

            GeoJsonConverter.Write(jsonWriter, geometry);
            return(jsonWriter.Token.ToString());
        }
コード例 #10
0
        public override void SyncFromInst()
        {
            JTokenWriter tw             = new JTokenWriter();
            var          jsonSerializer = new JsonSerializer()
            {
                Culture               = CultureInfo.InvariantCulture,
                Converters            = { new RGBPixelConverter() },
                MissingMemberHandling = MissingMemberHandling.Error,
            };

            _extparams = JObject.FromObject(this.Inst, jsonSerializer);
        }
コード例 #11
0
        /// <summary>
        /// Generates GeoJson for the given feature collection.
        /// </summary>
        public static string ToGeoJson(this IEnumerable <Feature> featureCollection)
        {
            if (featureCollection == null)
            {
                throw new ArgumentNullException("featureCollection");
            }

            var jsonWriter = new JTokenWriter();

            GeoJsonConverter.Write(jsonWriter, featureCollection);
            return(jsonWriter.Token.ToString());
        }
コード例 #12
0
        /// <summary>
        /// Generates GeoJson for the given feature.
        /// </summary>
        /// <param name="feature"></param>
        public static string ToGeoJson(this Feature feature)
        {
            if (feature == null)
            {
                throw new ArgumentNullException("feature");
            }

            var jsonWriter = new JTokenWriter();

            GeoJsonConverter.Write(jsonWriter, feature);
            return(jsonWriter.Token.ToString());
        }
コード例 #13
0
        /// <summary>
        /// Generates GeoJson for the given geometry collection.
        /// </summary>
        /// <param name="geometryCollection"></param>
        public static string ToGeoJson(this MultiPolygon geometryCollection)
        {
            if (geometryCollection == null)
            {
                throw new ArgumentNullException("geometryCollection");
            }

            var jsonWriter = new JTokenWriter();

            GeoJsonConverter.Write(jsonWriter, geometryCollection);
            return(jsonWriter.Token.ToString());
        }
コード例 #14
0
ファイル: JsonFilter.cs プロジェクト: ejball/FaithlifeJson
        /// <summary>
        /// Filters data from the specified token.
        /// </summary>
        /// <param name="token">The input token.</param>
        /// <returns>The output token.</returns>
        public JToken FilterToken(JToken token)
        {
            if (token == null)
            {
                return(null);
            }

            var tokenWriter = new JTokenWriter();

            token.WriteTo(CreateFilteredJsonWriter(tokenWriter));
            return(tokenWriter.Token);
        }
コード例 #15
0
        public static string ToGeoJson(this GeometryCollection geometryCollection)
        {
            if (geometryCollection == null)
            {
                throw new ArgumentNullException("geometryCollection");
            }
            JTokenWriter       jtokenWriter        = new JTokenWriter();
            GeometryCollection geometryCollection1 = geometryCollection;

            GeoJsonConverter.Write((JsonWriter)jtokenWriter, geometryCollection1);
            return(jtokenWriter.Token.ToString());
        }
コード例 #16
0
        public static string ToGeoJson(this LineString geometry)
        {
            if (geometry == null)
            {
                throw new ArgumentNullException("geometry");
            }
            JTokenWriter jtokenWriter = new JTokenWriter();
            LineString   geometry1    = geometry;

            GeoJsonConverter.Write((JsonWriter)jtokenWriter, geometry1);
            return(jtokenWriter.Token.ToString());
        }
コード例 #17
0
        public static string ToGeoJson(this FeatureCollection featureCollection)
        {
            if (featureCollection == null)
            {
                throw new ArgumentNullException("featureCollection");
            }
            JTokenWriter      jtokenWriter       = new JTokenWriter();
            FeatureCollection featureCollection1 = featureCollection;

            GeoJsonConverter.Write((JsonWriter)jtokenWriter, (IEnumerable <Feature>)featureCollection1);
            return(jtokenWriter.Token.ToString());
        }
コード例 #18
0
 private JToken CreateJToken(JsonReader reader, JsonContract contract)
 {
     ValidationUtils.ArgumentNotNull(reader, "reader");
     if (contract != null && contract.UnderlyingType == typeof(JRaw))
     {
         return(JRaw.Create(reader));
     }
     using (JTokenWriter jTokenWriter = new JTokenWriter())
     {
         jTokenWriter.WriteToken(reader);
         return(jTokenWriter.Token);
     }
 }
コード例 #19
0
        public static Task <JToken?> SaveContractMetadata(Uri uri, string scriptHash, AbiContract contractMetadata)
        {
            var serializer = new JsonSerializer();

            using var writer = new JTokenWriter();
            serializer.Serialize(writer, contractMetadata);
            if (writer.Token == null)
            {
                throw new ApplicationException($"Could not serialize {nameof(contractMetadata)}");
            }

            return(RpcCall(uri, "express-save-contract-metadata", new JArray(scriptHash, writer.Token)));
        }
コード例 #20
0
ファイル: MtSQLite.cs プロジェクト: imtect/Revit_FloorTag
        public static JToken readerToJson(SQLiteDataReader reader)
        {
            JTokenWriter jwrite = new JTokenWriter();

            jwrite.WriteStartObject();
            for (int i = 0; i < reader.FieldCount; ++i)
            {
                jwrite.WritePropertyName(reader.GetName(i));
                jwrite.WriteValue(reader.GetValue(i));
            }
            jwrite.WriteEndObject();
            return(jwrite.Token);
        }
コード例 #21
0
        public JToken Serialize(object value)
        {
            if (value == null)
            {
                return(new JValue((object)null));
            }

            using (JTokenWriter jtokenWriter = new JTokenWriter())
            {
                mSerializer.Serialize(jtokenWriter, value);
                return(jtokenWriter.Token);
            }
        }
コード例 #22
0
        private JObject WriteJson(TObject value)
        {
            var jsonSerializer = new JsonSerializer()
            {
                Converters = { Converter }
            };

            using (var jsonWriter = new JTokenWriter())
            {
                Converter.WriteJson(jsonWriter, value, jsonSerializer);
                return((JObject)jsonWriter.Token);
            }
        }
コード例 #23
0
        public async Task WriteCommentAsync()
        {
            JTokenWriter writer = new JTokenWriter();

            await writer.WriteStartArrayAsync();

            await writer.WriteCommentAsync("fail");

            await writer.WriteEndArrayAsync();

            StringAssert.AreEqual(@"[
  /*fail*/]", writer.Token.ToString());
        }
コード例 #24
0
        public static JObject GetAccTransByAccId(string accId, string fromDate = null, string toDate = null)
        {
            List <AccountSummary>     accSummary = new List <AccountSummary>();
            ReportsAccountingEntities db         = new ReportsAccountingEntities();
            var spResult = db.GetAccountDetailsByAccId(accId, fromDate == "" ? null : fromDate, toDate == "" ? null : toDate).ToList();

            JTokenWriter pJTokenWriter = new JTokenWriter();
            JObject      ordersJson    = new JObject();

            pJTokenWriter.WriteStartObject();
            pJTokenWriter.WritePropertyName("data");
            pJTokenWriter.WriteStartArray();
            foreach (var item in spResult)
            {
                pJTokenWriter.WriteStartObject();
                pJTokenWriter.WritePropertyName("AccountId");
                pJTokenWriter.WriteValue(item.AccountId);

                pJTokenWriter.WritePropertyName("CreateDate");
                pJTokenWriter.WriteValue(item.CreateDate.ToString("dd/MM/yyyy"));

                pJTokenWriter.WritePropertyName("CreateBy");
                pJTokenWriter.WriteValue(item.UserName);

                pJTokenWriter.WritePropertyName("DebitAmount");
                pJTokenWriter.WriteValue(item.DebitAmount);

                pJTokenWriter.WritePropertyName("CreditAmount");
                pJTokenWriter.WriteValue(item.CreditAmount);

                pJTokenWriter.WritePropertyName("CurrencySign");
                pJTokenWriter.WriteValue(item.CurrencySign);

                pJTokenWriter.WritePropertyName("TransactionName");
                pJTokenWriter.WriteValue(item.TransactionName);

                pJTokenWriter.WritePropertyName("TransactionNameAr");
                pJTokenWriter.WriteValue(item.TransactionNameAr);

                pJTokenWriter.WritePropertyName("ReceiptNotes");
                //pJTokenWriter.WriteValue(item.ReceiptNotes);
                pJTokenWriter.WriteValue("");

                pJTokenWriter.WriteEndObject();
            }

            pJTokenWriter.WriteEndArray();
            pJTokenWriter.WriteEndObject();
            ordersJson = (JObject)pJTokenWriter.Token;
            return(ordersJson);
        }
コード例 #25
0
        public void DateTimeZoneHandling()
        {
            JTokenWriter writer = new JTokenWriter
            {
                DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
            };

            writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));

            JValue   value = (JValue)writer.Token;
            DateTime dt    = (DateTime)value.Value;

            Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
        }
コード例 #26
0
        public void WriteRawValue()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartArray();
            writer.WriteRawValue("fail");
            writer.WriteRawValue("fail");
            writer.WriteEndArray();

            Assert.AreEqual(@"[
  fail,
  fail
]", writer.Token.ToString());
        }
コード例 #27
0
        internal static JObject ToJObject(this PackageSpec spec)
        {
            using (var jsonWriter = new JTokenWriter())
                using (var writer = new JsonObjectWriter(jsonWriter))
                {
                    writer.WriteObjectStart();

                    PackageSpecWriter.Write(spec, writer);

                    writer.WriteObjectEnd();

                    return((JObject)jsonWriter.Token);
                }
        }
コード例 #28
0
        private static JObject WriteLockFile(LockFile lockFile)
        {
            var json = new JObject
            {
                [VersionProperty]   = new JValue(lockFile.Version),
                [TargetsProperty]   = JsonUtility.WriteObject(lockFile.Targets, WriteTarget),
                [LibrariesProperty] = JsonUtility.WriteObject(lockFile.Libraries, WriteLibrary),
                [ProjectFileDependencyGroupsProperty] = JsonUtility.WriteObject(lockFile.ProjectFileDependencyGroups, WriteProjectFileDependencyGroup)
            };

            if (lockFile.PackageFolders?.Any() == true)
            {
                json[PackageFoldersProperty] = JsonUtility.WriteObject(lockFile.PackageFolders, WriteFileItem);
            }

            if (lockFile.Version >= 2)
            {
                if (lockFile.PackageSpec != null)
                {
                    using (var jsonWriter = new JTokenWriter())
                        using (var writer = new JsonObjectWriter(jsonWriter))
                        {
                            writer.WriteObjectStart();

                            PackageSpecWriter.Write(lockFile.PackageSpec, writer);

                            writer.WriteObjectEnd();

                            json[PackageSpecProperty] = (JObject)jsonWriter.Token;
                        }
                }
            }

            if (lockFile.Version >= 3)
            {
                if (lockFile.LogMessages.Count > 0)
                {
                    var projectPath = lockFile.PackageSpec?.RestoreMetadata?.ProjectPath;
                    json[LogsProperty] = WriteLogMessages(lockFile.LogMessages, projectPath);
                }
            }

            if (lockFile.CentralTransitiveDependencyGroups.Any())
            {
                JToken token = WriteCentralTransitiveDependencyGroup(lockFile.CentralTransitiveDependencyGroups);
                json[CentralTransitiveDependencyGroupsProperty] = (JObject)token;
            }

            return(json);
        }
コード例 #29
0
        public async Task DateTimeZoneHandlingAsync()
        {
            JTokenWriter writer = new JTokenWriter
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            await writer.WriteValueAsync(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));

            JValue   value = (JValue)writer.Token;
            DateTime dt    = (DateTime)value.Value;

            Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
        }
コード例 #30
0
        /// <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)
            {
                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;
        }
コード例 #31
0
        private JToken CreateJObject(JsonReader reader)
        {
            ValidationUtils.ArgumentNotNull(reader, "reader");

            // this is needed because we've already read inside the object, looking for metadata properties
            using (JTokenWriter writer = new JTokenWriter())
            {
                writer.WriteStartObject();

                do
                {
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        string propertyName = (string)reader.Value;
                        do
                        {
                            if (!reader.Read())
                                break;
                        } while (reader.TokenType == JsonToken.Comment);

                        if (CheckPropertyName(reader, propertyName))
                            continue;

                        writer.WritePropertyName(propertyName);
                        writer.WriteToken(reader, true, true);
                    }
                    else if (reader.TokenType == JsonToken.Comment)
                    {
                        // eat
                    }
                    else
                    {
                        writer.WriteEndObject();
                        return writer.Token;
                    }
                } while (reader.Read());

                throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
            }
        }
コード例 #32
0
        private JToken CreateJToken(JsonReader reader, JsonContract contract)
        {
            ValidationUtils.ArgumentNotNull(reader, "reader");

            if (contract != null && contract.UnderlyingType == typeof(JRaw))
            {
                return JRaw.Create(reader);
            }
            else
            {
                JToken token;
                using (JTokenWriter writer = new JTokenWriter())
                {
                    writer.WriteToken(reader);
                    token = writer.Token;
                }

                return token;
            }
        }