示例#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
        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);
            }
        }
        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
        /// <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));
        }
        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
        /// <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);
     }
 }
        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
        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);
            }
        }
        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);
        }
        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;
        }
        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.");
            }
        }
        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;
            }
        }