/// <summary>
        /// Serialize an object implementing IDictionary.  The serialized data is similar to a regular
        /// object, except that the keys of the dictionary are used instead of properties.
        /// </summary>
        /// <param name="data">the dictionary object</param>
        /// <param name="currentPath">object's path</param>
        /// <param name="serializer">the serializer instance, used to serialize keys and values</param>
        public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
        {
            IDictionary dictionary = (IDictionary)data;
            Type itemType = typeof(object);
            Type genericDictionary = null;

            if ((genericDictionary = dictionary.GetType().GetInterface(typeof(IDictionary<,>).Name)) != null)
            {
                itemType = genericDictionary.GetGenericArguments()[1];
            }

            ObjectExpression expression = new ObjectExpression();
            foreach (DictionaryEntry pair in dictionary)
            {
                //may not work in all cases
                object value = pair.Value;
                Expression valueExpr = serializer.Serialize(value, currentPath.Append(pair.Key.ToString()));
                if (value != null && !ReflectionUtils.AreEquivalentTypes(value.GetType(), itemType))
                {
                    valueExpr = new CastExpression(value.GetType(), valueExpr);
                }
                expression.Add(pair.Key.ToString(), valueExpr);
            }
            return expression;
        }
コード例 #2
0
 protected virtual Expression GetColumnExpression(DataColumn dc, JsonPath jsonPath, IExpressionBuilder serializer)
 {
     ObjectExpression column = new ObjectExpression();
     // just DataType and column for now
     column.Add("DataType", serializer.Serialize(dc.DataType, jsonPath.Append("DataType")));
     column.Add("ColumnName", serializer.Serialize(dc.ColumnName, jsonPath.Append("ColumnName")));
     return column;
 }
コード例 #3
0
 public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
 {
     DataTable table = (DataTable) data;
     ObjectExpression tableExpr = new ObjectExpression();
     tableExpr.Add("TableName", serializer.Serialize(table.TableName, currentPath.Append("TableName")));
     tableExpr.Add("Columns", GetColumnsExpression(table, currentPath.Append("Columns"), serializer));
     tableExpr.Add("Rows", GetRowsExpression(table, currentPath, serializer));
     return tableExpr;
 }
コード例 #4
0
 protected virtual Expression GetColumnsExpression(DataTable table, JsonPath currentPath, IExpressionBuilder serializer)
 {
     ArrayExpression columns = new ArrayExpression();
     int colCount = 0;
     foreach (DataColumn dc in table.Columns)
     {
         columns.Add(GetColumnExpression(dc, currentPath.Append(colCount), serializer));
         colCount++;
     }
     return columns;
 }
コード例 #5
0
        /// <summary>
        /// Creates an json object expression from object data.
        /// </summary>
        /// <param name="data">the data to serialize</param>
        /// <param name="currentPath">current path to the object</param>
        /// <param name="serializer">serializer instance used to serialize key values</param>
        /// <returns>json object expression</returns>
        public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
        {
             TypeData handler = Config.GetTypeHandler(data.GetType());

            ObjectExpression expression = new ObjectExpression();

            foreach (IPropertyData prop in handler.Properties)
            {
                GenerateItemExpression(data, currentPath, serializer, expression, prop);
            }
            return expression;
        }
コード例 #6
0
        /// <summary>
        /// Serialize the given object at the current indent level.  The path to the object is represented by
        /// currentPath such as "this.name", etc.  This is an internal method that can be called recursively.
        /// </summary>
        /// <param name="value">the object to serialize</param>
        /// <param name="currentPath">the current path for reference writing</param>
        public Expression Serialize(object value, JsonPath currentPath, IJsonTypeConverter converter)
        {
            if (value == null)
            {
                return new NullExpression();
            }
            else
            {
                IExpressionHandler objHandler;
                bool isReferencable = _config.IsReferenceableType(value.GetType());
                if (converter != null)
                {
                    TypeConverterExpressionHandler converterHandler = (TypeConverterExpressionHandler)_config.ExpressionHandlers.Find(typeof(TypeConverterExpressionHandler));
                    isReferencable = converterHandler.IsReferenceable(value, converter);
                    objHandler = converterHandler;
                }
                else
                {
                    objHandler = _config.ExpressionHandlers.GetHandler(value);
                    isReferencable = objHandler.IsReferenceable(value);
                }

                if (isReferencable)
                {
                    Expression expr = HandleReference(value, currentPath);
                    if (expr != null)
                        return expr;
                }

                ISerializationCallback callback = value as ISerializationCallback;
                if (callback != null)
                    callback.OnBeforeSerialization();

                try
                {
                    if (converter != null)
                    {
                        return ((TypeConverterExpressionHandler)objHandler).GetExpression(value, converter, currentPath, this);
                    }
                    else
                    {
                        SetCanReference(value);
                        return objHandler.GetExpression(value, currentPath, this);
                    }
                }
                finally
                {
                    if (callback != null)
                        callback.OnAfterSerialization();
                }
            }
        }
コード例 #7
0
        public void SelectEnumerableValuesUsingScalarPathFromJson_Expected_EnumerableValue()
        {
            string testData = Given();

            IPath path = new JsonPath("Motto", "Motto");

            JsonNavigator JsonNavigator = new JsonNavigator(testData);

            string       actual   = string.Join("|", JsonNavigator.SelectEnumerable(path).Select(o => o.ToString().Trim()));
            const string expected = "Eat lots of cake";

            Assert.AreEqual(expected, actual);
        }
コード例 #8
0
        public void Example9()
        {
            var input = "$..book[?(@.price<10)]";
            var path  = JsonPath.Parse(input);

            var result = path.Evaluate(_instance);

            Assert.IsNull(result.Error);
            Assert.AreEqual(2, result.Matches.Count);
            Assert.AreEqual("Sayings of the Century", result.Matches[0].Value.GetProperty("title").GetString());
            Assert.AreEqual("Moby Dick", result.Matches[1].Value.GetProperty("title").GetString());
            Assert.AreEqual(input, path.ToString());
        }
コード例 #9
0
        public void SelectEnumerableValuesUsingEnumerablePathFromJson_Expected_EnumerableValue()
        {
            string testData = Given();

            IPath path = new JsonPath("Departments().Name", "Departments.Name");

            JsonNavigator JsonNavigator = new JsonNavigator(testData);

            string       actual   = string.Join("|", JsonNavigator.SelectEnumerable(path).Select(o => o.ToString().Trim()));
            const string expected = "Dev|Accounts";

            Assert.AreEqual(expected, actual);
        }
コード例 #10
0
ファイル: JsonPathTests.cs プロジェクト: won21kr/Warewolf
        public void CreateEnumerablePathSegmentFromJProperty_Expected_EnumerableJsonPathSegment()
        {
            JProperty jProperty = new JProperty("EnumerableProperty", new JArray(
                                                    new JObject(new JProperty("ScalarProperty", "ScalarValue"),
                                                                new JProperty("ScalarProperty1", "ScalarValue1"))));
            JsonPath     path    = new JsonPath();
            IPathSegment segment = path.CreatePathSegment(jProperty);

            const bool expected = true;
            bool       actual   = segment.IsEnumarable;

            Assert.AreEqual(expected, actual);
        }
コード例 #11
0
        public void FilterOnBooks_ReturnsCorrectResult(string path, params string[] expected)
        {
            string input = TestDataLoader.Store();
            IReadOnlyList <JsonElement> result = JsonPath.ExecutePath(path, input);

            Assert.Equal(expected.Length, result.Count);
            string[] resultJsons = result.Select(x => JsonSerializer.Serialize(x)).Select(x => x.RemoveWhiteSpace()).ToArray();

            foreach (string e in expected)
            {
                Assert.Contains(_bookJsons[e], resultJsons);
            }
        }
コード例 #12
0
        public void SelectScalarValueUsingScalarPathFromJson_Expected_ScalarValue()
        {
            var testData = Given();

            IPath namePath = new JsonPath("Name", "Name");

            var JsonNavigator = new JsonNavigator(testData);

            var          actual   = JsonNavigator.SelectScalar(namePath).ToString();
            const string expected = "Dev2";

            Assert.AreEqual(expected, actual);
        }
コード例 #13
0
        public void RecordsetListHelper_SplitRecordsetAndFieldNames_WhenPathContainsScalar_SingleLevel_ShouldConvertToField()
        {
            //------------Setup for test--------------------------
            var jsonPath = new JsonPath();

            jsonPath.ActualPath = "ScalarValue";
            //------------Execute Test---------------------------
            var splitRecordsetAndFieldNames = RecordsetListHelper.SplitRecordsetAndFieldNames(jsonPath);

            //------------Assert Results-------------------------
            Assert.AreEqual("", splitRecordsetAndFieldNames.Item1);
            Assert.AreEqual("ScalarValue", splitRecordsetAndFieldNames.Item2);
        }
コード例 #14
0
        public void RecordsetListHelper_SplitRecordsetAndFieldNames_WhenPathContainsEndingField_MultiLevel_ShouldConvertToField()
        {
            //------------Setup for test--------------------------
            var jsonPath = new JsonPath();

            jsonPath.ActualPath = "OneRecordset().AnotherRecset().AndAnotherRecset";
            //------------Execute Test---------------------------
            var splitRecordsetAndFieldNames = RecordsetListHelper.SplitRecordsetAndFieldNames(jsonPath);

            //------------Assert Results-------------------------
            Assert.AreEqual("OneRecordset_AnotherRecset", splitRecordsetAndFieldNames.Item1);
            Assert.AreEqual("AndAnotherRecset", splitRecordsetAndFieldNames.Item2);
        }
コード例 #15
0
        public void Example3()
        {
            var input = "$.store.*";
            var path  = JsonPath.Parse(input);

            var result = path.Evaluate(_instance);

            Assert.IsNull(result.Error);
            Assert.AreEqual(2, result.Matches.Count);
            Assert.AreEqual(4, result.Matches[0].Value.EnumerateArray().Count());
            Assert.AreEqual(2, result.Matches[1].Value.EnumerateObject().Count());
            Assert.AreEqual(input, path.ToString());
        }
コード例 #16
0
        public void SelectEnumerableValuesUsingEnumerablePathFromJson_WherePathMapsToPrimitiveEnumerable_Expected_EnumerableValue()
        {
            string testData = Given();

            IPath path = new JsonPath("PrimitiveRecordset()", "PrimitiveRecordset");

            JsonNavigator JsonNavigator = new JsonNavigator(testData);

            string       actual   = string.Join("|", JsonNavigator.SelectEnumerable(path).Select(o => o.ToString().Trim()));
            const string expected = "RandomData|RandomData1";

            Assert.AreEqual(expected, actual);
        }
コード例 #17
0
        public void SelectEnumerableValuesUsingEnumerablePathFromJson_WherePathMapsThroughNestedEnumerables_Expected_EnumerableValue()
        {
            var testData = Given();

            IPath path = new JsonPath("Departments().Employees().Name", "Departments.Employees.Name");

            var JsonNavigator = new JsonNavigator(testData);

            var          actual   = string.Join("|", JsonNavigator.SelectEnumerable(path).Select(o => o.ToString().Trim()));
            const string expected = "Brendon|Jayd|Bob|Joe";

            Assert.AreEqual(expected, actual);
        }
コード例 #18
0
        public void SelectScalarValueUsingEnumerablePathFromJson_Expected_ScalarValue()
        {
            string testData = Given();

            IPath namePath = new JsonPath("Departments().Employees().Name", "Departments.Employees.Name");

            JsonNavigator JsonNavigator = new JsonNavigator(testData);

            string       actual   = JsonNavigator.SelectScalar(namePath).ToString();
            const string expected = "Joe";

            Assert.AreEqual(expected, actual);
        }
コード例 #19
0
        public void SelectScalarValueUsingEnumerablePathFromJson_WherePathMapsToPrimitiveEnumerable_Expected_ScalarValue()
        {
            string testData = Given();

            IPath namePath = new JsonPath("PrimitiveRecordset()", "PrimitiveRecordset");

            JsonNavigator JsonNavigator = new JsonNavigator(testData);

            string       actual   = JsonNavigator.SelectScalar(namePath).ToString().Trim();
            const string expected = "RandomData1";

            Assert.AreEqual(expected, actual);
        }
コード例 #20
0
        public Expression HandleReference(object value, JsonPath CurrentPath)
        {
            if (!IsReferenceable(value))
            {
                return(null);
            }

            ReferenceInfo refInfo = null;

            if (_refs.ContainsKey(value))
            {
                /*
                 * This object has already been seen by the serializer so
                 * determine what to do with it.  If its part of the current path
                 * then its a circular reference and an error needs to be thrown or it should
                 * be ignored depending on the option. Otherwise write a reference to it
                 */
                refInfo = _refs[value];
                JsonPath refPath = refInfo.Path;
                switch (_context.ReferenceWritingType)
                {
                case SerializationContext.ReferenceOption.WriteIdentifier:
                    if (!refInfo.CanReference)
                    {
                        throw new InvalidOperationException("Can't reference object: " + refPath + " from " + CurrentPath + ", either it is a collection, or it has not been converted yet");
                    }

                    return(new ReferenceExpression(refPath));

                case SerializationContext.ReferenceOption.IgnoreCircularReferences:
                    if (CurrentPath.StartsWith(refPath))
                    {
                        return(new NullExpression());
                    }
                    break;

                case SerializationContext.ReferenceOption.ErrorCircularReferences:
                    if (CurrentPath.StartsWith(refPath))
                    {
                        throw new InvalidOperationException("Circular reference detected.  Current path: " + CurrentPath + ", reference to: " + refPath);
                    }
                    break;
                }
            }
            else
            {
                refInfo      = new ReferenceInfo(CurrentPath);
                _refs[value] = refInfo;
            }
            return(null);
        }
コード例 #21
0
        public void FromJson(JsonValue json, JsonSerializer serializer)
        {
            Path = JsonPath.Parse(json.Object["path"].String);
            var result = json.Object["result"];

            if (result.Type == JsonValueType.Boolean && !result.Boolean)
            {
                Result = new JsonArray();
            }
            else
            {
                Result = result.Array;
            }
        }
コード例 #22
0
ファイル: JsonNavigatorTests.cs プロジェクト: pyrodc/Warewolf
        public void SelectScalarValue_WithEnumerableSymbolAndSeperatorSymbol_Expected_PrimitiveRecordset()
        {
            IPath namePath = new JsonPath("().", "().");

            var JsonNavigator = new JsonNavigator(testData);

            var          actual   = JsonNavigator.SelectScalar(namePath).ToString();
            const string expected = @"""PrimitiveRecordset"": [
  ""\r\n        RandomData\r\n    "",
  ""\r\n        RandomData1\r\n    ""
]";

            Assert.AreEqual(expected, actual);
        }
コード例 #23
0
ファイル: JsonNode.cs プロジェクト: trevorhreed/DNS
        public JsonNode Put(string path, object entitySrc)
        {
            dynamic  entity = getEntity(entitySrc);
            JsonPath jPath  = new JsonPath(path);
            JsonNode node   = read(jPath.ParentPathParts, true);

            if (entity != null && entity.GetType() == OBJ_TYPE)
            {
                entity["$key"] = jPath.Key;
            }
            node.Value()[jPath.Key] = entity;
            Save();
            return(read(jPath.PathParts));
        }
コード例 #24
0
        protected override void Execute(CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();

            if (!string.IsNullOrEmpty(JsonString.Get <string>(context)) && !string.IsNullOrEmpty(JsonPath.Get <string>(context)))
            {
                JObject jsonObject = JObject.Parse(JsonString.Get <string>(context));
                JToken  token      = jsonObject.SelectToken(JsonPath.Get <string>(context));
                if (token != null)
                {
                    string value = (string)token;
                    Result_Text.Set(context, value);

                    Guid id = new Guid();
                    if (Guid.TryParse(value, out id))
                    {
                        this.Result_Guid.Set(context, value);
                    }

                    DateTime dateTime = new DateTime();
                    if (DateTime.TryParse(value, out dateTime))
                    {
                        this.Result_DateTime.Set(context, dateTime);
                    }

                    decimal decimalValue = new decimal();
                    if (decimal.TryParse(value, out decimalValue))
                    {
                        this.Result_Decimal.Set(context, decimalValue);
                        try
                        {
                            this.Result_Money.Set(context, new Money(decimalValue));
                        }
                        catch { }
                    }

                    double doubleValue = new double();
                    if (double.TryParse(value, out doubleValue))
                    {
                        this.Result_Double.Set(context, doubleValue);
                    }

                    int intValue = 0;
                    if (int.TryParse(value, out intValue))
                    {
                        this.Result_WholeNumber.Set(context, intValue);
                    }
                }
            }
        }
コード例 #25
0
        public void RecursiveFilterAndWildcardArrayFilter_ReturnsCorrectResult(string path, params string[] expected)
        {
            string input = TestDataLoader.Store();
            IReadOnlyList <JsonElement> result = JsonPath.ExecutePath(path, input);

            Assert.Equal(expected.Length, result.Count);

            foreach (JsonElement r in result)
            {
                Assert.Equal(JsonValueKind.String, r.ValueKind);
                string rString = r.GetString();
                Assert.Contains(rString, expected);
            }
        }
コード例 #26
0
        public void Example2()
        {
            var input = "$..author";
            var path  = JsonPath.Parse(input);

            var result = path.Evaluate(_instance);

            Assert.IsNull(result.Error);
            Assert.AreEqual(4, result.Matches.Count);
            Assert.AreEqual("Nigel Rees", result.Matches[0].Value.GetString());
            Assert.AreEqual("Evelyn Waugh", result.Matches[1].Value.GetString());
            Assert.AreEqual("Herman Melville", result.Matches[2].Value.GetString());
            Assert.AreEqual("J. R. R. Tolkien", result.Matches[3].Value.GetString());
            Assert.AreEqual(input, path.ToString());
        }
コード例 #27
0
        // Test with these:
        // OBSOLETE DATA:
        // http://localhost:51080/ArtistVideo/Get/
        // http://localhost:51080/ArtistVideo/Get/Artist%200
        // http://localhost:51080/ArtistVideo/Get/?title=Video%201%201%20title

        public string Get(string[] id = null)
        {
            // Instantiate my homemade JSONPath Services object.  It does all the work:
            JsonPath jsonPathServices = new JsonPath();

            // Get the arguments from the command line URL and prepare them for usage.  Pass
            // them to the JSONPath query and execute it.  Return the result in JSON form:
            string response = jsonPathServices.QueryJsonPathMain((HttpRequestWrapper)Request);

            // NOTE: The core JSON Path module has a bug for this data-type only.  Rather than
            // open that can of worms, I will simply patch the JSON:
            response = response.Replace("}]},", "},");

            return(response);
        }
コード例 #28
0
ファイル: ParsingFails.cs プロジェクト: m1kl/Manatee.Json
 public static void Run(string text)
 {
     Assert.Throws <JsonPathSyntaxException>(() =>
     {
         try
         {
             Console.WriteLine($"\n{JsonPath.Parse(text)}");
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
             throw;
         }
     });
 }
コード例 #29
0
        public void GoessnerExample3Parsed()
        {
            var path     = JsonPath.Parse("$.store.*");
            var expected = new JsonArray
            {
                new JsonArray
                {
                    new JsonObject
                    {
                        { "category", "reference" },
                        { "author", "Nigel Rees" },
                        { "title", "Sayings of the Century" },
                        { "price", 8.95 }
                    },
                    new JsonObject
                    {
                        { "category", "fiction" },
                        { "author", "Evelyn Waugh" },
                        { "title", "Sword of Honour" },
                        { "price", 12.99 }
                    },
                    new JsonObject
                    {
                        { "category", "fiction" },
                        { "author", "Herman Melville" },
                        { "title", "Moby Dick" },
                        { "isbn", "0-553-21311-3" },
                        { "price", 8.99 }
                    },
                    new JsonObject
                    {
                        { "category", "fiction" },
                        { "author", "J. R. R. Tolkien" },
                        { "title", "The Lord of the Rings" },
                        { "isbn", "0-395-19395-8" },
                        { "price", 22.99 }
                    }
                },
                new JsonObject
                {
                    { "color", "red" },
                    { "price", 19.95 }
                }
            };
            var actual = path.Evaluate(GoessnerData);

            Assert.AreEqual(expected, actual);
        }
コード例 #30
0
        /// <summary>
        /// Check to see if an expectation is met.
        /// </summary>
        /// <param name="key">The name of the expectation being checked.</param>
        /// <param name="actualValue">The value for the expectation to check.</param>
        /// <param name="expectedValues">Can either be a single value or an array of values that are considered valid.</param>
        /// <param name="detectedErrors">A collection of validation errors that will be added to when errors are found.</param>
        /// <returns></returns>
        private static bool ExpectationSatisfied(string key, object actualValue, object expectedValues, List <ValidationError> detectedErrors)
        {
            if (null == key)
            {
                throw new ArgumentNullException("key");
            }
            if (null == detectedErrors)
            {
                throw new ArgumentNullException("detectedErrors");
            }

            if (actualValue == null && expectedValues != null)
            {
                detectedErrors.Add(new ValidationError(ValidationErrorCode.ExpectationConditionFailed, null, "Expectation {0}={1} failed. Actual value was null and a value was expected.", key, expectedValues));
                return(false);
            }

            if (expectedValues == null)
            {
                return(true);
            }

            if (null != (expectedValues as IList <JToken>))
            {
                if (((IList <JToken>)expectedValues).Any(possibleValue => JsonPath.TokenEquals(possibleValue, actualValue)))
                {
                    return(true);
                }
            }
            else
            {
                var token = expectedValues as JToken;
                if (token != null)
                {
                    if (JsonPath.TokenEquals(token, actualValue))
                    {
                        return(true);
                    }
                }
                else if (actualValue.Equals(expectedValues))
                {
                    return(true);
                }
            }

            detectedErrors.Add(new ValidationError(ValidationErrorCode.ExpectationConditionFailed, null, "Expectation {0} = {1} failed. Actual value: {2}", key, expectedValues, actualValue));
            return(false);
        }
コード例 #31
0
ファイル: InspectorComponent.cs プロジェクト: fremag/nats-ui
 private void TestJson()
 {
     try
     {
         IReadOnlyList <JsonElement> result = JsonPath.ExecutePath(Model.Expression, Model.Data);
         Model.Result = JsonSerializer.Serialize(result, new JsonSerializerOptions {
             WriteIndented = true
         });
     }
     catch (Exception e)
     {
         var msg = $"Failed to apply Json path: {e.Message}";
         Logger.Error(msg);
         Model.Result = msg;
     }
 }
コード例 #32
0
ファイル: JsonNavigatorTests.cs プロジェクト: pyrodc/Warewolf
        public void SelectEnumerableValuesAsRelatedUsingEnumerablePathFromJson_Where_PathsContainASinglePathWhichIsScalar_Expected_FlattenedDataWithValueFromScalarPath()
        {
            IPath path  = new JsonPath("Name", "Name");
            var   paths = new List <IPath> {
                path
            };

            var JsonNavigator = new JsonNavigator(testData);

            var data = JsonNavigator.SelectEnumerablesAsRelated(paths);

            const string expected = "Dev2";
            var          actual   = string.Join("|", data[path].Select(s => s.ToString().Trim()));

            Assert.AreEqual(expected, actual);
        }
コード例 #33
0
ファイル: JsonNavigatorTests.cs プロジェクト: pyrodc/Warewolf
        public void SelectEnumerableValuesAsRelatedUsingEnumerablePathFromJson_Where_PathsContainASinglePathWhichIsEnumerable_Expected_FlattenedDataWithValuesFromEnumerablePath()
        {
            IPath path  = new JsonPath("Departments().Employees().Name", "Departments.Employees.Name");
            var   paths = new List <IPath> {
                path
            };

            var JsonNavigator = new JsonNavigator(testData);

            var data = JsonNavigator.SelectEnumerablesAsRelated(paths);

            const string expected = "Brendon|Jayd|Bob|Joe";
            var          actual   = string.Join("|", data[path].Select(s => s.ToString().Trim()));

            Assert.AreEqual(expected, actual);
        }
コード例 #34
0
        public void LessThanOrEqualFilterOnIntWithDecimal_ReturnsCorrectResult()
        {
            string input = @"
                {
                    ""object"": {
                        ""arrays"": [ { ""amount"": 10 } ]
                    }
                }
            ";

            ExpressionList expression = ExpressionList.TokenizeAndParse("$.object.arrays[?(@.amount >= 10.0)]");

            IReadOnlyList <JsonElement> result = JsonPath.ExecutePath(expression, input);

            Assert.Equal(1, result.Count);
        }
コード例 #35
0
        public void Example4()
        {
            var input = "$.store..price";
            var path  = JsonPath.Parse(input);

            var result = path.Evaluate(_instance);

            Assert.IsNull(result.Error);
            Assert.AreEqual(5, result.Matches.Count);
            Assert.AreEqual(8.95m, result.Matches[0].Value.GetDecimal());
            Assert.AreEqual(12.99m, result.Matches[1].Value.GetDecimal());
            Assert.AreEqual(8.99m, result.Matches[2].Value.GetDecimal());
            Assert.AreEqual(22.99m, result.Matches[3].Value.GetDecimal());
            Assert.AreEqual(19.95m, result.Matches[4].Value.GetDecimal());
            Assert.AreEqual(input, path.ToString());
        }
コード例 #36
0
        protected virtual Expression GetExpression(IEnumerable Items, Type ItemType, JsonPath CurrentPath, ISerializerHandler serializer)
        {
            int index = 0;

            ArrayExpression expression = new ArrayExpression();
            foreach (object value in Items)
            {
                Expression itemExpr = serializer.Serialize(value, CurrentPath.Append(index));
                if (value != null && !ReflectionUtils.AreEquivalentTypes(value.GetType(), ItemType))
                {
                    itemExpr = new CastExpression(value.GetType(), itemExpr);
                }
                expression.Add(itemExpr);
                index++;
            }
            return expression;
        }
コード例 #37
0
 protected virtual Expression GetRowsExpression(DataTable table, JsonPath currentPath, IExpressionBuilder serializer)
 {
     ArrayExpression rowsExpr = new ArrayExpression();
     for (int i = 0; i < table.Rows.Count; i++)
     {
         DataRow row = table.Rows[i];
         object[] values = row.ItemArray;
         JsonPath rowPath = currentPath.Append(i);
         ArrayExpression rowExpr = new ArrayExpression();
         for (int j = 0; j < values.Length; j++)
         {
             rowExpr.Add(serializer.Serialize(values[j], rowPath.Append(j)));
         }
         rowsExpr.Add(rowExpr);
     }
     return rowsExpr;
 }
コード例 #38
0
        public string TryParse(string source, ref int index, ref JsonPath path)
        {
            if (path == null)
            {
                return("Start token not found.");
            }

            var error = source.GetSlices(ref index, out var slices);

            if (error != null)
            {
                return(error);
            }

            path = path.Array(slices.ToArray());
            return(null);
        }
コード例 #39
0
        public Expression HandleReference(object value, JsonPath CurrentPath)
        {
            if (!IsReferenceable(value))
                return null;

            ReferenceInfo refInfo = null;
            if (_refs.ContainsKey(value))
            {
                /*
                 * This object has already been seen by the serializer so
                 * determine what to do with it.  If its part of the current path
                 * then its a circular reference and an error needs to be thrown or it should
                 * be ignored depending on the option. Otherwise write a reference to it
                 */
                refInfo = _refs[value];
                JsonPath refPath = refInfo.Path;
                switch (_context.ReferenceWritingType)
                {
                    case SerializationContext.ReferenceOption.WriteIdentifier:
                        if (!refInfo.CanReference)
                            throw new InvalidOperationException("Can't reference object: " + refPath + " from " + CurrentPath + ", either it is a collection, or it has not been converted yet");

                        return new ReferenceExpression(refPath);
                    case SerializationContext.ReferenceOption.IgnoreCircularReferences:
                        if (CurrentPath.StartsWith(refPath))
                        {
                            return new NullExpression();
                        }
                        break;
                    case SerializationContext.ReferenceOption.ErrorCircularReferences:
                        if (CurrentPath.StartsWith(refPath))
                        {
                            throw new InvalidOperationException("Circular reference detected.  Current path: " + CurrentPath + ", reference to: " + refPath);
                        }
                        break;
                }
            }
            else
            {
                refInfo = new ReferenceInfo(CurrentPath);
                _refs[value] = refInfo;
            }
            return null;
        }
コード例 #40
0
 /// <summary>
 /// Generates an expression for an item and adds it to the object
 /// </summary>
 /// <param name="data">the item being serialized</param>
 /// <param name="currentPath">the current path to the object</param>
 /// <param name="serializer">serializer instance</param>
 /// <param name="expression">the object expression</param>
 /// <param name="prop">the property being serialized</param>
 protected virtual void GenerateItemExpression(object data, JsonPath currentPath, IExpressionBuilder serializer, ObjectExpression expression, IPropertyData prop)
 {
     object value = prop.GetValue(data);
     if (!prop.ShouldWriteValue(this.Config, value))
         return;
     Expression valueExpr;
     if (prop.HasConverter)
     {
         valueExpr = serializer.Serialize(value, currentPath.Append(prop.Alias), prop.TypeConverter);
     }
     else
     {
         valueExpr = serializer.Serialize(value, currentPath.Append(prop.Alias));
     }
     if (value != null && !ReflectionUtils.AreEquivalentTypes(value.GetType(), prop.PropertyType))
     {
         valueExpr = new CastExpression(value.GetType(), valueExpr);
     }
     expression.Add(prop.Alias, valueExpr);
 }
コード例 #41
0
        /// <summary>
        /// Serializes the data into a json array expression.
        /// </summary>
        /// <param name="data">the data to serialize</param>
        /// <param name="currentPath">the current path to the data</param>
        /// <param name="serializer">serializer instance to use to serialize list items</param>
        /// <returns>a json array expression representation</returns>
        public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
        {
            TypeData handler = Config.GetTypeHandler(data.GetType());

            CollectionHandler collectionHandler = handler.CollectionHandler;
            Type elemType = collectionHandler.GetItemType(handler.ForType);

            int index = 0;

            ArrayExpression expression = new ArrayExpression();
            foreach (object value in collectionHandler.GetEnumerable(data))
            {
                Expression itemExpr = serializer.Serialize(value, currentPath.Append(index));
                if (value != null && !ReflectionUtils.AreEquivalentTypes(value.GetType(), elemType))
                {
                    itemExpr = new CastExpression(value.GetType(), itemExpr);
                }
                expression.Add(itemExpr);
                index++;
            }
            return expression;
        }
コード例 #42
0
 public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
 {
     string value = ((DateTime)data).ToString(dateFormat, Culture);
     return new ValueExpression(value);
 }
コード例 #43
0
        /// <summary>
        /// Creates an json object expression from object data.
        /// </summary>
        /// <param name="data">the data to serialize</param>
        /// <param name="currentPath">current path to the object</param>
        /// <param name="serializer">serializer instance used to serialize key values</param>
        /// <returns>json object expression</returns>
        public override Expression GetExpression(object data, JsonPath currentPath, ISerializerHandler serializer)
        {
            TypeData handler = Context.GetTypeHandler(data.GetType());

            ObjectExpression expression = new ObjectExpression();

            foreach (IPropertyData prop in handler.Properties)
            {
                object value = prop.GetValue(data);
                Expression valueExpr;
                if (prop.HasConverter)
                {
                    valueExpr = serializer.Serialize(value, currentPath.Append(prop.Name), prop.TypeConverter);
                }
                else
                {
                    valueExpr = serializer.Serialize(value, currentPath.Append(prop.Name));
                }
                if (value != null && !ReflectionUtils.AreEquivalentTypes(value.GetType(), prop.PropertyType))
                {
                    valueExpr = new CastExpression(value.GetType(), valueExpr);
                }
                expression.Add(prop.Name, valueExpr);
            }
            return expression;
        }
コード例 #44
0
 /// <summary>
 /// Take an object and convert it to an expression to be serialized.  Child names/indexes should be appended to the
 /// currentPath before serializing child objects.
 /// </summary>
 /// <param name="data">the object to convert</param>
 /// <param name="CurrentPath">the current path to this object from the root, used for tracking references</param>
 /// <param name="serializer">serializer instance for serializing child objects</param>
 /// <returns>an expression which represents a json structure</returns>
 public abstract Expression GetExpression(object data, JsonPath currentPath, ISerializerHandler serializer);
コード例 #45
0
 public Expression Serialize(object value, JsonPath currentPath)
 {
     return Serialize(value, currentPath, null);
 }
コード例 #46
0
 /// <summary>
 /// Gets an expression for a value by first converting it with its registered type converter and then calling Serialize
 /// </summary>
 /// <param name="value">the value to generate an expression for</param>
 /// <param name="currentPath">the current path to the value</param>
 /// <param name="serializer">serializer instance</param>
 /// <returns>an expression for the value</returns>
 public override Expression GetExpression(object value, JsonPath currentPath, ISerializerHandler serializer)
 {
     TypeData handler = Context.TypeHandlerFactory[value.GetType()];
     IJsonTypeConverter converter = (handler.HasConverter ? handler.TypeConverter : (IJsonTypeConverter)value);
     return GetExpression(value, converter, currentPath, serializer);
 }
コード例 #47
0
 public ReferenceExpression(string ReferencePath)
 {
     this._path = new JsonPath(ReferencePath);
 }
コード例 #48
0
 public ReferenceVisitor(JsonPath RefID)
 {
     _refID = RefID;
 }
コード例 #49
0
 /// <summary>
 /// Converts a boolean value into a BooleanExpression
 /// </summary>
 /// <param name="data">the data to convert to an expression</param>
 /// <param name="currentPath">the current path to the object, ignored for BooleanExpression</param>
 /// <param name="serializer">serializer instance, ignored</param>
 /// <returns>a BooleanExpression</returns>
 public override Expression GetExpression(object data, JsonPath currentPath, ISerializerHandler serializer)
 {
     return new BooleanExpression(data);
 }
コード例 #50
0
 /// <summary>
 /// Returns a reference expression to the current data
 /// </summary>
 /// <param name="data">the object data</param>
 /// <param name="currentPath">current path to this object</param>
 /// <param name="serializer">serializer instance</param>
 /// <returns>reference expression</returns>
 public override Expression GetExpression(object data, JsonPath currentPath, ISerializerHandler serializer)
 {
     return serializer.HandleReference(data, currentPath);
 }
コード例 #51
0
 public ReferenceInfo(JsonPath Path)
 {
     this.Path = Path;
 }
コード例 #52
0
        /// <summary>
        /// Serialize the given object at the current indent level.  The path to the object is represented by
        /// currentPath such as "this.name", etc.  This is an internal method that can be called recursively.
        /// </summary>
        /// <param name="value">the object to serialize</param>
        /// <param name="currentPath">the current path for reference writing</param>
        public Expression Serialize(object value, JsonPath currentPath, IJsonTypeConverter converter)
        {
            if (value == null)
            {
                return new NullExpression();
            }
            else
            {

                Expression expr = HandleReference(value, currentPath);
                if (expr != null)
                    return expr;

                ISerializationCallback callback = value as ISerializationCallback;
                if (callback != null)
                    callback.OnBeforeSerialization();

                try
                {
                    //TODO: this is too early for converters
                    SetCanReference(value);    // regular object, can reference at any time
                    IExpressionHandler objHandler;
                    if (converter != null)
                    {
                        TypeConverterExpressionHandler converterHandler = (TypeConverterExpressionHandler)_context.ExpressionHandlers.Find(typeof(TypeConverterExpressionHandler));
                        //TODO: make sure it exists
                        return converterHandler.GetExpression(value, converter, currentPath, this);
                    }
                    objHandler = _context.ExpressionHandlers.GetHandler(value);
                    return objHandler.GetExpression(value, currentPath, this);
                }
                finally
                {
                    if (callback != null)
                        callback.OnAfterSerialization();
                }
            }
        }
コード例 #53
0
 public void VisitComplexBase(ComplexExpressionBase expression)
 {
     if (_refID.Top == JsonPath.Root)
     {
         if (expression.Parent != null)
         {
             throw new ArgumentException("Reference for this passed to object that is not at the root", "refID");
         }
     }
     else
     {
         // have to assume that the parent checked that we were the right reference
         // should only get here if we have a parent, if no parent we're not valid
         if (expression.Parent == null)
             throw new ArgumentException("Invalid reference", "refID");
     }
     // it is this object, check if we need to go further
     _refID = _refID.ChildReference();
     if (_refID.IsEmpty) {
         _expr = expression;
     }
 }
コード例 #54
0
        /// <summary>
        /// Parses a reference to an object
        /// </summary>
        /// <returns></returns>
        private Expression ParseReference()
        {
            JsonPath refID = new JsonPath();
            Token tok = ReadToken();
            if (tok != ReferenceStartToken && tok != OldReferenceStartToken)
                throw new ParseException(string.Format("Invalid starting token for ParseReference, Expected: {0} or {1}, got: {2}", ReferenceStartToken, OldReferenceStartToken,tok));            
            while (PeekToken() == PeriodToken || PeekToken() == LSquareToken)
            {
                tok = ReadToken(); // separator "."
                if (tok == PeriodToken)
                    tok = ReadToken(); // type part

                if (tok == LSquareToken)
                {
                    refID = refID.Append(ReadToken().value); // index
                    ReadToken(); // ]
                }
                else if (tok.type == TokenType.Identifier)
                {
                    refID = refID.Append(tok.value);
                }
                else
                {
                    throw new ParseException("Invalid Reference, must be an identifier or array value: " + tok);
                }                
            }
            return new ReferenceExpression(refID);
        }
コード例 #55
0
 public ReferenceExpression(JsonPath ReferencePath)
 {
     this._path = ReferencePath;
 }
コード例 #56
0
 /// <summary>
 /// GetExpression is not valid for a CastExpression.  CastExpressions should be created directly
 /// during serialization whenever type information is needed.
 /// </summary>
 /// <param name="data">data to serialize</param>
 /// <param name="currentPath">the current path to the object</param>
 /// <param name="serializer">serializer instance</param>
 /// <returns>expression</returns>
 /// <exception cref="InvalidOperationException">This will throw an exception if called</exception>
 public override Expression GetExpression(object data, JsonPath currentPath, ISerializerHandler serializer)
 {
     throw new InvalidOperationException("CastObjectHandler should not be called during Serialization");
 }
コード例 #57
0
 /// <summary>
 /// Gets an expression for a value by first converting it with a specific type converter and then calling Serialize.  This
 /// method can be called directly when using a Property Converter
 /// </summary>
 /// <param name="value">the value to generate an expression for</param>
 /// <param name="converter">the type converter to use for conversion</param>
 /// <param name="currentPath">the current path to the value</param>
 /// <param name="serializer">serializer instance</param>
 /// <returns>an expression for the value</returns>
 public Expression GetExpression(object value, IJsonTypeConverter converter, JsonPath currentPath, ISerializerHandler serializer)
 {
     object convertedObject = converter.ConvertFrom(value, Context);
     // call serialize again in case the new type has a converter
     Expression expr = serializer.Serialize(convertedObject, currentPath, null);
     serializer.SetCanReference(value);   // can't reference inside the object
     return expr;
 }
コード例 #58
0
 public override Expression GetExpression(object data, JsonPath CurrentPath, ISerializerHandler serializer)
 {
     return GetExpression((IEnumerable)data, GetItemType(data.GetType()), CurrentPath, serializer);
 }
コード例 #59
0
 /// <summary>
 /// Creates a null expression
 /// </summary>
 /// <param name="data">the data</param>
 /// <param name="currentPath">current path</param>
 /// <param name="serializer">serializer instance</param>
 /// <returns>NullExpression</returns>
 public override Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer)
 {
     return new NullExpression();
 }
コード例 #60
0
 /// <summary>
 /// Take an object and convert it to an expression to be serialized.  Child names/indexes should be appended to the
 /// currentPath before serializing child objects.
 /// </summary>
 /// <param name="data">the object to convert</param>
 /// <param name="CurrentPath">the current path to this object from the root, used for tracking references</param>
 /// <param name="serializer">serializer instance for serializing child objects</param>
 /// <returns>an expression which represents a json structure</returns>
 public abstract Expression GetExpression(object data, JsonPath currentPath, IExpressionBuilder serializer);