Пример #1
0
        public override bool IsValid(JsonSchemaDefinitions definitions, JsonValue value, JsonSchemaCallback callback)
        {
            bool succeeded = true;
            JsonObject target = value as JsonObject;

            if (target == null)
                return true;

            foreach (string property in target.GetKeys())
            {
                if (items.ContainsKey(property))
                {
                    JsonPathSegment segment = new JsonPropertySegment(property);
                    JsonSchemaCallback scope = callback.Scope(segment);
                    JsonSchemaRule rule = items[property];

                    if (rule.IsValid(definitions, target.Get(property), scope) == false)
                    {
                        callback.Add(scope);
                        succeeded = false;
                    }
                }
            }

            return succeeded;
        }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     IList<RateLimitStatus> limits = new List<RateLimitStatus>();
     JsonValue resourcesValue = value.GetValue("resources");
     if (resourcesValue != null)
     {
         foreach(string resourceFamily in resourcesValue.GetNames())
         {
             JsonValue resourceFamilyValue = resourcesValue.GetValue(resourceFamily);
             foreach (string resourceEndpoint in resourceFamilyValue.GetNames())
             {
                 JsonValue rateLimitValue = resourceFamilyValue.GetValue(resourceEndpoint);
                 limits.Add(new RateLimitStatus()
                     {
                         ResourceFamily = resourceFamily,
                         ResourceEndpoint = resourceEndpoint,
                         WindowLimit = rateLimitValue.GetValue<int>("limit"),
                         RemainingHits = rateLimitValue.GetValue<int>("remaining"),
                         ResetTime = FromUnixTime(rateLimitValue.GetValue<long>("reset"))
                     });
             }
         }
     }
     return limits;
 }
Пример #3
0
        public override bool IsValid(JsonSchemaDefinitions definitions, JsonValue value, JsonSchemaCallback callback)
        {
            if (rule.IsValid(definitions, value, JsonSchemaCallback.Ignore()) == false)
                return true;

            return callback.Fail(value, "The NOT condition should not be valid.");
        }
        public object Deserialize(JsonValue value, JsonMapper mapper)
        {
            Tweet tweet = new Tweet();

            tweet.ID = value.GetValue<long>("id");
            tweet.Text = value.GetValue<string>("text");
            JsonValue fromUserValue = value.GetValue("user");
            string dateFormat;
            if (fromUserValue != null)
            {
                tweet.FromUser = fromUserValue.GetValue<string>("screen_name");
                tweet.FromUserId = fromUserValue.GetValue<long>("id");
                tweet.ProfileImageUrl = fromUserValue.GetValue<string>("profile_image_url");
                dateFormat = TIMELINE_DATE_FORMAT;
            }
            else
            {
                tweet.FromUser = value.GetValue<string>("from_user");
                tweet.FromUserId = value.GetValue<long>("from_user_id");
                tweet.ProfileImageUrl = value.GetValue<string>("profile_image_url");
                dateFormat = SEARCH_DATE_FORMAT;
            }
            tweet.CreatedAt = JsonUtils.ToDateTime(value.GetValue<string>("created_at"), dateFormat);
            tweet.Source = value.GetValue<string>("source");
            JsonValue toUserIdValue = value.GetValue("in_reply_to_user_id");
            tweet.ToUserId = (toUserIdValue != null) ? toUserIdValue.GetValue<long?>() : null;
            JsonValue languageCodeValue = value.GetValue("iso_language_code");
            tweet.LanguageCode = (languageCodeValue != null) ? languageCodeValue.GetValue<string>() : null;
            JsonValue inReplyToStatusIdValue = value.GetValue("in_reply_to_status_id");
            tweet.InReplyToStatusId = ((inReplyToStatusIdValue != null) && !inReplyToStatusIdValue.IsNull) ? inReplyToStatusIdValue.GetValue<long?>() : null;

            return tweet;
        }
Пример #5
0
        private static bool HasType(JsonValue value, string type)
        {
            switch (type)
            {
                case "object":
                    return value is JsonObject;

                case "array":
                    return value is JsonArray;

                case "string":
                    return value is JsonText;

                case "boolean":
                    return value is JsonTrue || value is JsonFalse;

                case "null":
                    return value is JsonNull;

                case "integer":
                    return value is JsonNumber && value.As<JsonNumber>().IsInteger();

                case "number":
                    return value is JsonNumber;

                default:
                    return false;
            }
        }
Пример #6
0
        private void WriteObject(JsonValue obj)
        {
            currentDepth++;
            if (currentDepth > MAX_DEPTH)
                throw new JsonException("Serializer encountered maximum depth of " + MAX_DEPTH);
            output.Append('{');

            bool append = false;
            foreach (KeyValuePair<string, JsonValue> kv in obj.store as Dictionary<string, JsonValue>)
            {
                if (kv.Value.type == JsonType.None
                    || (serializeNulls == false && kv.Value.type == JsonType.Null)
                    || (serializeZeros == false && kv.Value.IsZero()))
                    continue;

                if (append)
                    output.Append(',');

                WritePair(kv.Key, kv.Value);
                append = true;
            }

            currentDepth--;
            output.Append('}');
            currentDepth--;
        }
        public object Deserialize(JsonValue json, JsonMapper mapper)
        {
            var job = new Job();

            var clientJson = json.GetValue("client");

            job.Id = json.GetValueOrDefault<string>("id", "");
            job.Title = json.GetValueOrDefault<string>("title", "");
            job.Snippet = json.GetValueOrDefault<string>("snippet", "");
            job.Skills = deserializeSkills(json.GetValues("skills"));
            job.Category = json.GetValueOrDefault<string>("category", "");
            job.Subcategory = json.GetValueOrDefault<string>("subcategory", "");
            job.JobType = json.GetValueOrDefault<string>("job_type", "");
            job.Duration = json.GetValueOrDefault<string>("duration", "");
            job.Budget = json.GetValueOrDefault<string>("budget", "");
            job.Workload = json.GetValueOrDefault<string>("workload", "");
            job.Status = json.GetValueOrDefault<string>("job_status", "");
            job.Url = json.GetValueOrDefault<string>("url", "");
            job.DateCreated = json.GetValueOrDefault<DateTime>("date_created", DateTime.MinValue);

            if (clientJson != null)
            {
                job.Client.Country = clientJson.GetValueOrDefault<string>("country", "");
                job.Client.FeedbackRating = clientJson.GetValueOrDefault<float>("feedback", 0);
                job.Client.ReviewCount = clientJson.GetValueOrDefault<int>("reviews_count", 0);
                job.Client.JobCount = clientJson.GetValueOrDefault<int>("jobs_posted", 0);
                job.Client.HireCount = clientJson.GetValueOrDefault<int>("past_hires", 0);
                job.Client.PaymentVerificationStatus = clientJson.GetValueOrDefault<string>("payment_verification_status", "");
            }

            return job;
        }
        public override object Deserialize(JsonValue json, JsonMapper mapper)
        {
            LinkedInFullProfile profile = (LinkedInFullProfile)base.Deserialize(json, mapper);

            profile.Associations = json.GetValueOrDefault<string>("associations", String.Empty);
            profile.BirthDate = DeserializeLinkedInDate(json.GetValue("dateOfBirth"));
            profile.ConnectionsCount = json.GetValue<int>("numConnections");
            profile.Distance = json.GetValue<int>("distance");
            profile.Educations = DeserializeEducations(json.GetValue("educations"));
            profile.Email = json.GetValueOrDefault<string>("emailAddress");
            profile.Honors = json.GetValueOrDefault<string>("honors", String.Empty);
            profile.ImAccounts = DeserializeImAccounts(json.GetValue("imAccounts"));
            profile.Interests = json.GetValueOrDefault<string>("interests", String.Empty);
            profile.IsConnectionsCountCapped = json.GetValue<bool>("numConnectionsCapped");
            JsonValue locationJson = json.GetValue("location");
            profile.CountryCode = locationJson.GetValue("country").GetValue<string>("code");
            profile.Location = locationJson.GetValueOrDefault<string>("name", String.Empty);
            profile.MainAddress = json.GetValueOrDefault<string>("mainAddress", String.Empty);
            profile.PhoneNumbers = DeserializePhoneNumbers(json.GetValue("phoneNumbers"));
            profile.Positions = DeserializePositions(json.GetValue("positions"));
            profile.ProposalComments = json.GetValueOrDefault<string>("proposalComments", String.Empty);
            profile.Recommendations = DeserializeRecommendations(json.GetValue("recommendationsReceived"), mapper);
            profile.RecommendersCount = json.GetValueOrDefault<int?>("numRecommenders");
            profile.Specialties = json.GetValueOrDefault<string>("specialties", String.Empty);
            profile.TwitterAccounts = DeserializeTwitterAccounts(json.GetValue("twitterAccounts"));
            profile.UrlResources = DeserializeUrlResources(json.GetValue("memberUrlResources"));
            profile.Certifications = DeserializeCertifications(json.GetValue("certifications"));
            profile.Skills = DeserializeSkills(json.GetValue("skills"));
            profile.Publications = DeserializePublications(json.GetValue("publications"));         
            profile.Courses = DeserializeCourses(json.GetValue("courses"));
            profile.Languages = DeserializeLanguages(json.GetValue("languages"));

            return profile;
        }
Пример #9
0
        public UserModel(JsonValue json, IJsonContext context) {
            var dict = JsonDictionary.FromValue(json);

            bool wasRelaxed = context.RelaxedNumericConversion;
            context.RelaxedNumericConversion = true;

            UserName = dict.Get<string>("username", context);
            AccountType = dict.Get<string>("account_type", context, "free");
            SignUpDate = new DateTime(1970,1,1).AddSeconds(dict.Get<double>("sign_up_date", context));

            if (dict.Items.ContainsKey("profile_image"))
                ProfileImage = new Uri(dict.Get<string>("profile_image", context), UriKind.Absolute);

            Sets = dict.Get<List<SetModel>>("sets", context);
            FavouriteSets = dict.Get<List<SetModel>>("favorite_sets", context);
            Groups = dict.Get<List<GroupModel>>("groups", context);

            if (dict.Items.ContainsKey("statistics")) {
                var stats = dict.GetSubDictionary("statistics");
                foreach (var k in stats.Items) {
                    switch (k.Key) {
                        case "study_session_count": StudySessionCount = context.FromJson<int>(k.Value); break;
                        case "message_count": MessageCount = context.FromJson<int>(k.Value); break;
                        case "total_answer_count": TotalAnswerCount = context.FromJson<int>(k.Value); break;
                        case "public_sets_created": PublicSetsCreated = context.FromJson<int>(k.Value); break;
                        case "public_terms_entered": PublicTermsEntered = context.FromJson<int>(k.Value); break;
                    }
                }
            }

            context.RelaxedNumericConversion = wasRelaxed;
        }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			Photo photo = null;
			if ( json != null && !json.IsNull )
			{
				photo = new Photo();
				photo.ID          = json.ContainsName("id"          ) ? json.GetValue<string>("id"      ) : String.Empty;
				photo.Name        = json.ContainsName("name"        ) ? json.GetValue<string>("name"    ) : String.Empty;
				photo.Icon        = json.ContainsName("icon"        ) ? json.GetValue<string>("icon"    ) : String.Empty;
				photo.Picture     = json.ContainsName("picture"     ) ? json.GetValue<string>("picture" ) : String.Empty;
				photo.Source      = json.ContainsName("source"      ) ? json.GetValue<string>("source"  ) : String.Empty;
				photo.Height      = json.ContainsName("height"      ) ? json.GetValue<int   >("height"  ) : 0;
				photo.Width       = json.ContainsName("width"       ) ? json.GetValue<int   >("width"   ) : 0;
				photo.Link        = json.ContainsName("link"        ) ? json.GetValue<string>("link"    ) : String.Empty;
				photo.Position    = json.ContainsName("position"    ) ? json.GetValue<int   >("position") : 0;
				photo.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue<string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;
				photo.UpdatedTime = json.ContainsName("updated_time") ? JsonUtils.ToDateTime(json.GetValue<string>("updated_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;
				
				photo.From        = mapper.Deserialize<Reference>(json.GetValue("from" ));
				photo.Place       = mapper.Deserialize<Page     >(json.GetValue("place"));
				photo.Tags        = mapper.Deserialize<List<Tag>>(json.GetValue("tags" ));
				photo.Images      = mapper.Deserialize<List<Photo.Image>>(json.GetValue("images"));
				if ( photo.Images != null )
				{
					int i = 0;
					if ( photo.Images.Count >= 5 ) photo.OversizedImage = photo.Images[i++];
					if ( photo.Images.Count >= 1 ) photo.SourceImage    = photo.Images[i++];
					if ( photo.Images.Count >= 2 ) photo.AlbumImage     = photo.Images[i++];
					if ( photo.Images.Count >= 3 ) photo.SmallImage     = photo.Images[i++];
					if ( photo.Images.Count >= 4 ) photo.TinyImage      = photo.Images[i++];
				}
			}
			return photo;
		}
Пример #11
0
        static JsonValue ReadArray(string json, ref int i)
        {
            i++; // Skip the '['
            SkipWhitespace(json, ref i);

            JsonValue arrayval = new JsonValue();
            arrayval.Type = JsonType.Array;

            bool expectingValue = false;
            while (json[i] != ']') {
                expectingValue = false;
                arrayval.Add(ReadValue(json, ref i));
                SkipWhitespace(json, ref i);
                if (json[i] == ',') {
                    expectingValue = true;
                    i++;
                    SkipWhitespace(json, ref i);
                } else if (json[i] != ']') {
                    throw new InvalidJsonException("Expected end array token at column " + i + "!");
                }
            }

            if (expectingValue) {
                throw new InvalidJsonException("Unexpected end array token at column " + i + "!");
            }

            i++; // Skip the ']'
            return arrayval;
        }
Пример #12
0
 public UserMentionEntity(JsonValue json) : base(json)
 {
     Id = json["id"].AsLong();
     ScreenName = json["screen_name"].AsStringOrNull();
     Name = json["name"].AsStringOrNull();
     FullText = DisplayText = "@" + ScreenName;
 }
Пример #13
0
        public override bool IsValid(JsonSchemaDefinitions definitions, JsonValue value, JsonSchemaCallback callback)
        {
            int count = 0;
            List<JsonSchemaCallback> scopes = new List<JsonSchemaCallback>();

            foreach (JsonSchemaRule rule in rules)
            {
                JsonSchemaCallback scope = callback.Scope();

                if (rule.IsValid(definitions, value, scope))
                    count++;

                if (scope.Count > 0)
                    scopes.Add(scope);

                if (count > 1)
                    break;
            }

            if (count == 1)
                return true;

            if (count > 1)
                return callback.Fail(value, $"Exactly one schema should be valid, but {count} schemas were valid.");

            foreach (JsonSchemaCallback scope in scopes)
                callback.Add(scope);

            return callback.Fail(value, "Exactly one schema should be valid, but nothing was valid.");
        }
        object IJsonDeserializer.Deserialize(JsonValue json, JsonMapper mapper)
        {
            var results = new SearchResults();
            var userJson = json.GetValue("auth_user");
            var pagingJson = json.GetValue("paging");
            var jobsJson = json.GetValue("jobs");


            results.ServerTime = json.GetValueOrDefault<long>("server_time");
            results.ProfileAccess = json.GetValueOrDefault<string>("profile_access");

            if (userJson != null)
            {
                results.AuthUser.FirstName = userJson.GetValue<string>("first_name");
                results.AuthUser.LastName = userJson.GetValue<string>("last_name");
                results.AuthUser.Username = userJson.GetValue<string>("uid");
                results.AuthUser.Email = userJson.GetValue<string>("mail");
                results.AuthUser.TimeZone = userJson.GetValue<string>("timezone");
                results.AuthUser.TimeZoneOffset = userJson.GetValue<string>("timezone_offset");
            }

            if (pagingJson != null)
            {
                results.Paging.Count = pagingJson.GetValue<int>("count");
                results.Paging.Offset = pagingJson.GetValue<int>("offset");
                results.Paging.Total = pagingJson.GetValue<int>("total");
            }

            results.Jobs = mapper.Deserialize<List<Job>>(jobsJson);

            return results;
        }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			Comment comment = null;
			if ( json != null && !json.IsNull )
			{
				comment = new Comment();
				comment.ID          = json.ContainsName("id"          ) ? json.GetValue<string>("id"     ) : String.Empty;
				comment.Message     = json.ContainsName("message"     ) ? json.GetValue<string>("message") : String.Empty;
				comment.CreatedTime = json.ContainsName("created_time") ? JsonUtils.ToDateTime(json.GetValue<string>("created_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;

				comment.From        = mapper.Deserialize<Reference      >(json.GetValue("from" ));
				// 04/12/2012 Paul.  Likes is a connection object, so make sure that this is not the same likes property value. 
				// 04/15/2012 Paul.  Likes can be a number or an array. 
				JsonValue jsonLikes = json.GetValue("likes");
				if ( jsonLikes != null && !jsonLikes.IsNull )
				{
					if ( jsonLikes.IsArray )
					{
						comment.Likes       = mapper.Deserialize<List<Reference>>(jsonLikes);
						comment.LikesCount  = (comment.Likes != null) ? comment.Likes.Count : 0;
					}
					else if ( jsonLikes.IsNumber )
					{
						comment.LikesCount = jsonLikes.GetValue<int>();
					}
				}
			}
			return comment;
		}
Пример #16
0
        private void WriteArray(JsonValue obj)
        {
            currentDepth++;
            if (currentDepth > MAX_DEPTH)
                throw new JsonException("Serializer encountered maximum depth of " + MAX_DEPTH);
            output.Append('[');

            bool append = false;
            foreach (JsonValue v in obj.store as List<JsonValue>)
            {
                if (append)
                    output.Append(',');

                if (v.type == JsonType.None || (v.type == JsonType.Null && serializeNulls == false))
                    append = false;
                else
                {
                    WriteValue(v);
                    append = true;
                }
            }

            currentDepth--;
            output.Append(']');
            currentDepth--;
        }
 public object Deserialize(JsonValue json, JsonMapper mapper)
 {
     SimilarPlaces similarPlaces = new SimilarPlaces(mapper.Deserialize<IList<Place>>(json));
     similarPlaces.PlacePrototype = new PlacePrototype();
     similarPlaces.PlacePrototype.CreateToken = json.GetValue("result").GetValue<string>("token");
     return similarPlaces;
 }
 public override object Deserialize(JsonValue json, JsonMapper mapper)
 {
     JsonValue peopleJson = json.ContainsName("people") ? json.GetValue("people") : json;
     LinkedInProfiles profiles = (LinkedInProfiles)base.Deserialize(peopleJson, mapper);
     profiles.Profiles = mapper.Deserialize<IList<LinkedInProfile>>(peopleJson);
     return profiles;
 }
Пример #19
0
 /// <summary>
 /// Gets the JSON array holding the entries of the given feed.
 /// </summary>
 /// <param name="testConfiguration">The test configuration to consider.</param>
 /// <param name="feed">The JSON value representing the feed.</param>
 /// <returns>A JSON array with the items in a feed.</returns>
 public static JsonArray GetTopLevelFeedItemsArray(WriterTestConfiguration testConfiguration, JsonValue feed)
 {
     feed = feed.Object().PropertyValue("value");
     ExceptionUtilities.CheckObjectNotNull(feed, "The specified JSON Lite payload is not wrapped in the expected \"value\": wrapper.");
     ExceptionUtilities.Assert(feed.JsonType == JsonValueType.JsonArray, "Feed contents must be an array.");
     return (JsonArray)feed;
 }
Пример #20
0
        public override bool IsValid(JsonSchemaDefinitions definitions, JsonValue value, JsonSchemaCallback callback)
        {
            bool succeeded = true;
            JsonObject target = value as JsonObject;

            if (target == null)
                return true;

            foreach (Regex pattern in items.Keys)
            {
                foreach (string property in target.GetKeys().Where(x => pattern.IsMatch(x)))
                {
                    JsonSchemaRule rule = items[pattern];
                    JsonPathSegment segment = new JsonPropertySegment(property);
                    JsonSchemaCallback scope = callback.Scope(segment);

                    if (rule.IsValid(definitions, target.Get(property), callback) == false)
                    {
                        callback.Add(scope);
                        succeeded = false;
                    }
                }
            }

            return succeeded;
        }
Пример #21
0
 internal TwitterSavedSearch(JsonValue json)
 {
     Id = json["id_str"].AsString().ParseLong();
     CreatedAt = json["created_at"].AsString()
         .ParseDateTime(ParsingExtension.TwitterDateTimeFormat);
     Query = json["query"].AsString().AssertNotNull("json.query could not be null.");
     Name = json["name"].AsString() ?? Query;
 }
Пример #22
0
		public Speaker (JsonValue json) : this()
		{
			Id = json["id"];
			Name = json["name"];
			TwitterHandle = json["twitterHandle"];
			Bio = json["bio"];
			HeadshotUrl = json["headshotUrl"];
		}
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     return new FileRef()
     {
         Value = value.GetValue<string>("copy_ref"),
         ExpireDate = JsonUtils.ToDropboxDateTime(value.GetValue<string>("expires")).Value
     };
 }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     return new DropboxLink()
     {
         Url = value.GetValue<string>("url"),
         ExpireDate = JsonUtils.ToDropboxDateTime(value.GetValue<string>("expires")).Value
     };
 }
Пример #25
0
 public void PrettyPrintSimpleObject()
 {
     JsonValue test = new JsonValue {
         { "test", 1 },
         { "test2", 2 }
     };
     Assert.That(JsonWriter.ToJson(test, true), Is.EqualTo("{\n\t\"test\": 1,\n\t\"test2\": 2\n}"));
 }
Пример #26
0
 public UrlEntity(JsonValue json) : base(json)
 {
     Url = json["url"].AsStringOrNull();
     DisplayUrl = json["display_url"].AsStringOrNull();
     ExpandedUrl = json["expanded_url"].AsStringOrNull();
     DisplayText = DisplayUrl ?? String.Empty;
     FullText = ExpandedUrl ?? DisplayText;
 }
 public object Deserialize(JsonValue json, JsonMapper mapper)
 {
     JsonValue values = json.GetValue("values");
     return new NetworkStatistics()
     {
         FirstDegreeCount = values.GetValue<int>(0),
         SecondDegreeCount = values.GetValue<int>(1),
     };
 }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     IList<Tweet> tweets = new List<Tweet>();
     foreach (JsonValue itemValue in value.GetValues())
     {
         tweets.Add(mapper.Deserialize<Tweet>(itemValue));
     }
     return tweets;
 }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     IList<Place> places = new List<Place>();
     foreach (JsonValue itemValue in value.GetValue("result").GetValues("places"))
     {
         places.Add(mapper.Deserialize<Place>(itemValue));
     }
     return places;
 }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     IList<DirectMessage> directMessages = new List<DirectMessage>();
     foreach (JsonValue itemValue in value.GetValues())
     {
         directMessages.Add(mapper.Deserialize<DirectMessage>(itemValue));
     }
     return directMessages;
 }
Пример #31
0
 /**
  * Set raw JsonValue object for a key
  */
 public void PutRaw(string key, JsonValue value)
 {
     raw_values[key] = value;
 }
Пример #32
0
 public override void Setup(JsonValue settings)
 {
     base.Setup(settings);
     scourge = settings["scourge"].String(Scourge.OfUnknown);
 }
Пример #33
0
 /// <summary>
 /// Builds an object from a <see cref="JsonValue"/>.
 /// </summary>
 /// <param name="json">The <see cref="JsonValue"/> representation of the object.</param>
 /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional
 /// serialization of values.</param>
 public void FromJson(JsonValue json, JsonSerializer serializer)
 {
     Value = serializer.Deserialize <JsonSchema>(json);
 }
Пример #34
0
 public void ShouldTreatArraysOfDifferentLengthAsUnequal()
 {
     Assert.False(comparier.Equals(JsonValue.Parse("[1, 42]"), JsonValue.Parse("[1, 44]")));
 }
Пример #35
0
 public IJsonValue GetValueByName(string name)
 {
     return(dataObject.GetNamedValue(name, JsonValue.CreateNullValue()));
 }
Пример #36
0
 public SchemaValidationResults Validate(T schema, JsonValue json, JsonValue root)
 {
     return(new SchemaValidationResults(GetDependencies(schema).SelectMany(d => d.Validate(json, root).Errors)));
 }
Пример #37
0
        // Parse a json string and compare to the expected value
        void CheckDouble(double expected, string json)
        {
            double jvalue = (double)JsonValue.Parse(json);

            Assert.AreEqual(expected, jvalue);
        }
Пример #38
0
        public static IJsonValue ToJsonValue(this object source)
        {
            if (source == null)
            {
                return(NullValue);
            }

            var jsonValue = source as IJsonValue;

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

            var convertibleJsonValue = source as IExportToJsonValue;

            if (convertibleJsonValue != null)
            {
                return(convertibleJsonValue.ExportToJsonObject());
            }

            var stringValue = source as string;

            if (stringValue != null)
            {
                if (string.IsNullOrEmpty(stringValue))
                {
                    return(EmptyStringValue);
                }

                return(JsonValue.CreateStringValue(stringValue));
            }

            if (source is Enum)
            {
                return(JsonValue.CreateStringValue(source.ToString()));
            }

            var timeSpan = source as TimeSpan?;

            if (timeSpan.HasValue)
            {
                return(JsonValue.CreateStringValue(timeSpan.ToString()));
            }

            var boolValue = source as bool?;

            if (boolValue.HasValue)
            {
                return(boolValue.Value ? TrueValue : FalseValue);
            }

            var dateTimeValue = source as DateTime?;

            if (dateTimeValue.HasValue)
            {
                return(JsonValue.CreateStringValue(dateTimeValue.Value.ToString("O")));
            }

            var array = source as IEnumerable;

            if (array != null)
            {
                var result = new JsonArray();
                foreach (var arrayEntry in array)
                {
                    result.Add(arrayEntry.ToJsonValue());
                }

                return(result);
            }

            if (source is double)
            {
                return(JsonValue.CreateNumberValue((double)source));
            }

            if (source is byte)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((byte)source)));
            }

            if (source is short)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((short)source)));
            }

            if (source is int)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((int)source)));
            }

            if (source is long)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((long)source)));
            }

            if (source is float)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((float)source)));
            }

            if (source is decimal)
            {
                return(JsonValue.CreateNumberValue(Convert.ToDouble((decimal)source)));
            }

            return(source.ToJsonObject());
        }
Пример #39
0
 /// <summary>
 ///     Returns the specified content to the client with the MIME type “application/json; charset=utf-8”.</summary>
 /// <param name="content">
 ///     Content to return to the client.</param>
 /// <param name="status">
 ///     HTTP status code to use in the response.</param>
 /// <param name="headers">
 ///     Headers to use in the response, or null to use default values.</param>
 public static HttpResponseContent Json(JsonValue content, HttpStatusCode status = HttpStatusCode._200_OK, HttpResponseHeaders headers = null)
 {
     return(Create(JsonValue.ToEnumerable(content), "application/json; charset=utf-8", status, headers));
 }
        public ActionResult Admin(IFormCollection formCollection)
        {
            try
            {
                string dataString = formCollection["mrctCode"] + "|" + formCollection["txn_id"] + "|" + formCollection["amount"] + "|" + formCollection["accNo"] + "|"
                                    + formCollection["custID"] + "|" + formCollection["mobNo"] + "|" + formCollection["email"] + "|" + formCollection["debitStartDate"] + "|" + formCollection["debitEndDate"]
                                    + "|" + formCollection["maxAmount"] + "|" + formCollection["amountType"] + "|" + formCollection["frequency"] + "|" + formCollection["cardNumber"] + "|"
                                    + formCollection["expMonth"] + "|" + formCollection["expYear"] + "|" + formCollection["cvvCode"] + "|" + formCollection["SALT"];
                string hh = GenerateSHA512String(dataString);
                //formCollection["authenticity_token"] = hh;

                var personlist = ToJSON(formCollection);
                // Pass the "personlist" object for conversion object to JSON string
                //string jsondata = new JavaScriptSerializer().Serialize(personlist);
                string jsondata = JsonConvert.SerializeObject(personlist);
                string path     = _env.WebRootPath;
                //string path = Server.MapPath("~/App_Data/");
                // Write that JSON to txt file,

                JsonValue json = JsonValue.Parse(jsondata);

                //  result = System.Web.Helpers.Json.parse(jsondata);
                //  FileStream SourceStream= System.IO.File.Open(path + "output.json",System.IO.FileMode.OpenOrCreate);
                //System.IO.File.WriteAllText(path + "\\output.json", json);
                System.IO.File.WriteAllText(path + "\\output.json", json);

                using (StreamReader r = new StreamReader(path + "\\output.json"))
                {
                    //json = r.ReadToEnd();
                    json = r.ReadToEnd();
                    var           jsonData = JObject.Parse(json).Children();
                    List <JToken> tokens   = jsonData.Children().ToList();
                    ViewBag.config_data = tokens;
                    r.Close();
                }

                List <SelectListItem> enbDisb = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "Enable", Value = "true"
                    },
                    new SelectListItem()
                    {
                        Text = "Disable", Value = "false"
                    }
                };

                List <SelectListItem> currencyCodes = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "INR", Value = "INR"
                    },
                    new SelectListItem()
                    {
                        Text = "USD", Value = "USD"
                    }
                };

                List <SelectListItem> paymentMode = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "all", Value = "all"
                    },
                    new SelectListItem()
                    {
                        Text = "cards", Value = "cards"
                    },
                    new SelectListItem()
                    {
                        Text = "netBanking", Value = "netBanking"
                    },
                    new SelectListItem()
                    {
                        Text = "UPI", Value = "UPI"
                    },
                    new SelectListItem()
                    {
                        Text = "imps", Value = "imps"
                    },
                    new SelectListItem()
                    {
                        Text = "wallets", Value = "wallets"
                    },
                    new SelectListItem()
                    {
                        Text = "cashCards", Value = "cashCards"
                    },
                    new SelectListItem()
                    {
                        Text = "NEFTRTGS", Value = "NEFTRTGS"
                    },
                    new SelectListItem()
                    {
                        Text = "emiBanks", Value = "emiBanks"
                    }
                };

                List <SelectListItem> typeOfPayment = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "TEST", Value = "TEST"
                    },
                    new SelectListItem()
                    {
                        Text = "LIVE", Value = "LIVE"
                    }
                };
                List <SelectListItem> amounttype = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "Fixed", Value = "Fixed"
                    },
                    new SelectListItem()
                    {
                        Text = "Variable", Value = "Variable"
                    }
                };
                List <SelectListItem> frequency = new List <SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Text = "Daily", Value = "DAIL"
                    },
                    new SelectListItem()
                    {
                        Text = "Weekly", Value = "WEEK"
                    },
                    new SelectListItem()
                    {
                        Text = "Monthly", Value = "MNTH"
                    },
                    new SelectListItem()
                    {
                        Text = "Quarterly", Value = "QURT"
                    },
                    new SelectListItem()
                    {
                        Text = "Semi annually", Value = "MIAN"
                    },
                    new SelectListItem()
                    {
                        Text = "Yearly", Value = "YEAR"
                    },
                    new SelectListItem()
                    {
                        Text = "Bi- monthly", Value = "BIMN"
                    },
                    new SelectListItem()
                    {
                        Text = "As and when presented", Value = "ADHO"
                    }
                };

                ViewBag.enbDisb       = enbDisb;
                ViewBag.currencyCodes = currencyCodes;
                ViewBag.paymentModes  = paymentMode;
                ViewBag.typeOfPayment = typeOfPayment;
                ViewBag.amounttype    = amounttype;
                ViewBag.frequency     = frequency;
            }
            catch (Exception ex)
            {
            }
            //  TempData["msg"] = "Json file Generated! check this in your App_Data folder";
            return(View());
        }
 /// <summary>
 /// Builds an object from a <see cref="JsonValue"/>.
 /// </summary>
 /// <param name="json">The <see cref="JsonValue"/> representation of the object.</param>
 /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional
 /// serialization of values.</param>
 public void FromJson(JsonValue json, JsonSerializer serializer)
 {
     Value = json.Boolean;
 }
Пример #42
0
        public AssetsQueryFixture()
        {
            mongoDatabase = mongoClient.GetDatabase("QueryTests");

            SetupJson();

            var assetRepository = new MongoAssetRepository(mongoDatabase);

            Task.Run(async() =>
            {
                await assetRepository.InitializeAsync();

                await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 0 }");
                await mongoDatabase.DropCollectionAsync("system.profile");

                var collection = assetRepository.GetInternalCollection();

                var assetCount = await collection.Find(new BsonDocument()).CountDocumentsAsync();

                if (assetCount == 0)
                {
                    var batch = new List <MongoAssetEntity>();

                    async Task ExecuteBatchAsync(MongoAssetEntity? entity)
                    {
                        if (entity != null)
                        {
                            batch.Add(entity);
                        }

                        if ((entity == null || batch.Count >= 1000) && batch.Count > 0)
                        {
                            await collection.InsertManyAsync(batch);

                            batch.Clear();
                        }
                    }

                    foreach (var appId in AppIds)
                    {
                        for (var i = 0; i < numValues; i++)
                        {
                            var fileName = i.ToString();

                            for (var j = 0; j < numValues; j++)
                            {
                                var tag = j.ToString();

                                var asset = new MongoAssetEntity
                                {
                                    Id    = Guid.NewGuid(),
                                    AppId = appId,
                                    Tags  = new HashSet <string> {
                                        tag
                                    },
                                    FileHash     = fileName,
                                    FileName     = fileName,
                                    FileSize     = 1024,
                                    IndexedAppId = appId.Id,
                                    IsDeleted    = false,
                                    IsProtected  = false,
                                    Metadata     = new AssetMetadata
                                    {
                                        ["value"] = JsonValue.Create(tag)
                                    },
                                    Slug = fileName,
                                };

                                await ExecuteBatchAsync(asset);
                            }
                        }
                    }

                    await ExecuteBatchAsync(null);
                }

                await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 2 }");
            }).Wait();

            AssetRepository = assetRepository;
        }
Пример #43
0
        [JavascriptInterface] // This is also needed in API 17+
        // to become consistent with Java/JS interop convention, the argument cannot be System.String.
        //the list might have diff business rules, so spin up a seperate class for it
        public void LoadMeterInformation(string meterInfo)
        {
            //fail checks first
            if (string.IsNullOrEmpty(meterInfo))
            {
                Toast.MakeText(_context, "No meter data supplied.", ToastLength.Long).Show();
                return;
            }

            try
            {
                var jsonMeter = JsonValue.Parse(meterInfo);

                //ALAN: they are stryingifying twice when sending the data over to us, so parse it again: Android.LoadMeterInformation(JSON.stringify(JSON.stringify(meterInfo))); remove once they fix this to only stringify once
                //UPDATE(12/28/2015): It looks like they updated this to only do it once:  Android.LoadMeterInformation(JSON.stringify(meterInfo));
                //BUT there were no enforcable meters at this time, so could not test. We shouldnt need the below try/catch and should be safe to remove.
                try
                {
                    if (jsonMeter != null)
                    {
                        jsonMeter = JsonValue.Parse(jsonMeter);
                    }
                }
                catch (Exception ex)
                {
                    //couldnt parse it again, hopefully means they fixed the stringify to only occur once. can parse it the same amount of times they stringify it, any more and will throw an exception.
                    //LoggingManager.LogApplicationError(ex, "PayBySpaceListFragment: Double Parse", "LoadMeterInformation");
                }

                if (jsonMeter == null)
                {
                    Toast.MakeText(_context, "Invalid format: meter data.", ToastLength.Long).Show();
                    //LoggingManager.LogApplicationError(null, "PayBySpaceListFragment: Invalid format: meter data", "LoadMeterInformation");
                    return;
                }

                //store the data in the context. not saving to the db anymore
                //DroidContext.XmlCfg.SetJsonValueObjectPaySpaceList(jsonMeter);
                //ExternalEnforcementInterfaces.SetWirelessEnforcementMode(ExternalEnforcementInterfaces.TWirelessEnforcementMode.wefPayBySpaceList, jsonMeter);

                #region Samples
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                ////////////////SAMPLES: here are some samples on how to get it out of the context//////////////////////
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //Get the GIS Meter JsonValue Object
                // var lastGISValue = DroidContext.XmlCfg.GetGISMeterJsonValueObject();

                // //get individual properties from it
                // //Get the meter ID (which is an int value):
                // var meterId = DroidContext.XmlCfg.GetGISMeterPropertyInt("MeterId");
                ////get meterName which is a string:
                // var meterName = DroidContext.XmlCfg.GetGISMeterPropertyString("MeterName");
                #endregion


                SwitchToParkingFormForEnforcement(Constants.GIS_PAYBYSPACE_LIST_FRAGMENT_TAG);
            }
            catch (Exception ex)
            {
                //LoggingManager.LogApplicationError(ex, "PayBySpaceListFragment", "LoadMeterInformation");
                Toast.MakeText(_context, "Error loading ticket data.", ToastLength.Long).Show();
            }
        }
Пример #44
0
 /// <summary>
 ///     Constructor for a key-value argument (not a file upload).</summary>
 /// <param name="name">
 ///     Name of the argument.</param>
 /// <param name="value">
 ///     Value of the argument. This value is encoded as JSON syntax.</param>
 /// <seealso cref="HArg(string,string)"/>
 /// <seealso cref="HArg(string,string,string,byte[])"/>
 public HArg(string name, JsonValue value)
 {
     Name  = name;
     Value = value.ToString();
 }
Пример #45
0
 public bool Applies(T schema, JsonValue json)
 {
     return(GetDependencies(schema) != null);
 }
Пример #46
0
        // Convert a number to json and parse the string, then compare the result to the original value
        void CheckDouble(double number)
        {
            double jvalue = (double)JsonValue.Parse(new JsonPrimitive(number).ToString());

            Assert.AreEqual(number, jvalue);              // should be exactly the same
        }
Пример #47
0
 public void AddOrChangePreferenceJson(string name, JsonValue value)
 {
     otherPreferencesJson[name] = value;
 }
Пример #48
0
        public void CheckNumbers()
        {
            CheckDouble(0, "0");
            CheckDouble(0, "-0");
            CheckDouble(0, "0.00");
            CheckDouble(0, "-0.00");
            CheckDouble(1, "1");
            CheckDouble(1.1, "1.1");
            CheckDouble(-1, "-1");
            CheckDouble(-1.1, "-1.1");
            CheckDouble(1e-10, "1e-10");
            CheckDouble(1e+10, "1e+10");
            CheckDouble(1e-30, "1e-30");
            CheckDouble(1e+30, "1e+30");

            CheckDouble(1, "\"1\"");
            CheckDouble(1.1, "\"1.1\"");
            CheckDouble(-1, "\"-1\"");
            CheckDouble(-1.1, "\"-1.1\"");

            CheckDouble(double.NaN, "\"NaN\"");
            CheckDouble(double.PositiveInfinity, "\"Infinity\"");
            CheckDouble(double.NegativeInfinity, "\"-Infinity\"");

            ExpectError("NaN");
            ExpectError("Infinity");
            ExpectError("-Infinity");

            Assert.AreEqual("1.1", new JsonPrimitive(1.1).ToString());
            Assert.AreEqual("-1.1", new JsonPrimitive(-1.1).ToString());
            Assert.AreEqual("1E-20", new JsonPrimitive(1e-20).ToString());
            Assert.AreEqual("1E+20", new JsonPrimitive(1e+20).ToString());
            Assert.AreEqual("1E-30", new JsonPrimitive(1e-30).ToString());
            Assert.AreEqual("1E+30", new JsonPrimitive(1e+30).ToString());
            Assert.AreEqual("\"NaN\"", new JsonPrimitive(double.NaN).ToString());
            Assert.AreEqual("\"Infinity\"", new JsonPrimitive(double.PositiveInfinity).ToString());
            Assert.AreEqual("\"-Infinity\"", new JsonPrimitive(double.NegativeInfinity).ToString());

            Assert.AreEqual("1E-30", JsonValue.Parse("1e-30").ToString());
            Assert.AreEqual("1E+30", JsonValue.Parse("1e+30").ToString());

            CheckDouble(1);
            CheckDouble(1.1);
            CheckDouble(1.25);
            CheckDouble(-1);
            CheckDouble(-1.1);
            CheckDouble(-1.25);
            CheckDouble(1e-20);
            CheckDouble(1e+20);
            CheckDouble(1e-30);
            CheckDouble(1e+30);
            CheckDouble(3.1415926535897932384626433);
            CheckDouble(3.1415926535897932384626433e-20);
            CheckDouble(3.1415926535897932384626433e+20);
            CheckDouble(double.NaN);
            CheckDouble(double.PositiveInfinity);
            CheckDouble(double.NegativeInfinity);
            CheckDouble(double.MinValue);
            CheckDouble(double.MaxValue);

            // A number which needs 17 digits (see http://stackoverflow.com/questions/6118231/why-do-i-need-17-significant-digits-and-not-16-to-represent-a-double)
            CheckDouble(18014398509481982.0);

            // Values around the smallest positive decimal value
            CheckDouble(1.123456789e-29);
            CheckDouble(1.123456789e-28);

            CheckDouble(1.1E-29, "0.000000000000000000000000000011");
            // This is being parsed as a decimal and rounded to 1e-28, even though it can be more accurately be represented by a double
            //CheckDouble (1.1E-28, "0.00000000000000000000000000011");
        }
Пример #49
0
 public bool Applies(IJsonSchema schema, JsonValue json)
 {
     return(json.Type == JsonValueType.Object && json.Object.ContainsKey("definitions"));
 }
        public async Task <IActionResult> UpdateDatamodel(string org, string app, string modelName)
        {
            SchemaKeywordCatalog.Add <InfoKeyword>();

            try
            {
                modelName = modelName.AsFileName();
            }
            catch
            {
                return(BadRequest("Invalid model name value."));
            }

            string filePath = $"App/models/{modelName}";

            using (Stream resource = Request.Body)
            {
                // Read the request body and deserialize to Json Schema
                using StreamReader streamReader = new StreamReader(resource);
                string content = await streamReader.ReadToEndAsync();

                TextReader textReader = new StringReader(content);
                JsonValue  jsonValue  = await JsonValue.ParseAsync(textReader);

                JsonSchema jsonSchemas = new Manatee.Json.Serialization.JsonSerializer().Deserialize <JsonSchema>(jsonValue);

                // Create the directory if it does not exist
                string appPath   = _repository.GetAppPath(org, app);
                string directory = appPath + Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // Serialize and store the Json Schema
                var          serializer = new Manatee.Json.Serialization.JsonSerializer();
                JsonValue    toar       = serializer.Serialize(jsonSchemas);
                byte[]       byteArray  = Encoding.UTF8.GetBytes(toar.ToString());
                MemoryStream jsonstream = new MemoryStream(byteArray);
                await _repository.WriteData(org, app, $"{filePath}.schema.json", jsonstream);

                // update meta data
                JsonSchemaToInstanceModelGenerator converter = new JsonSchemaToInstanceModelGenerator(org, app, jsonSchemas);
                ModelMetadata modelMetadata = converter.GetModelMetadata();
                string        root          = modelMetadata.Elements != null && modelMetadata.Elements.Count > 0 ? modelMetadata.Elements.Values.First(e => e.ParentElement == null).TypeName : null;
                _repository.UpdateApplicationWithAppLogicModel(org, app, modelName, "Altinn.App.Models." + root);
                _repository.UpdateModelMetadata(org, app, modelMetadata, modelName);

                // Convert to XML Schema and store in repository
                JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();
                XmlSchema       xmlschema       = jsonSchemaToXsd.CreateXsd(jsonSchemas);
                MemoryStream    xsdStream       = new MemoryStream();
                XmlTextWriter   xwriter         = new XmlTextWriter(xsdStream, new UpperCaseUtf8Encoding());
                xwriter.Formatting = Formatting.Indented;
                xwriter.WriteStartDocument(false);
                xmlschema.Write(xsdStream);
                await _repository.WriteData(org, app, $"{filePath}.xsd", xsdStream);

                // Generate updated C# model
                JsonMetadataParser modelGenerator = new JsonMetadataParser();
                string             classes        = modelGenerator.CreateModelFromMetadata(modelMetadata);
                byteArray = Encoding.UTF8.GetBytes(classes);
                MemoryStream stream = new MemoryStream(byteArray);
                await _repository.WriteData(org, app, $"{filePath}.cs", stream);
            }

            return(Ok());
        }
Пример #51
0
 public void ShouldTreatDifferentlySizedArraysAsUnequal()
 {
     Assert.False(comparier.Equals(JsonValue.Parse("[1, 42]"), JsonValue.Parse("[1, 42, 4]")));
 }
Пример #52
0
 public void UsedViaLinq()
 {
     _jsonArray.Should().Contain(JsonValue.Number(_array[0]));
     _jsonArray.Should().NotContain(JsonValue.Number(int.MinValue));
 }
Пример #53
0
 public GebruikerRecord(JsonValue record)
 {
     id = record["id"];
 }
Пример #54
0
 /// <summary>
 /// Builds an object from a <see cref="JsonValue"/>.
 /// </summary>
 /// <param name="json">The <see cref="JsonValue"/> representation of the object.</param>
 /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional
 /// serialization of values.</param>
 public void FromJson(JsonValue json, JsonSerializer serializer)
 {
     throw new NotImplementedException();
 }
Пример #55
0
 public void LoadWithTrailingComma2()
 {
     JsonValue.Parse("[{ \"a\": \"b\",}]");
 }
        public static JsonValue ReadAsJsonValue(this HttpContent content)
        {
            FX.ThrowIfNull(content, "content");

            return(JsonValue.Load(content.ContentReadStream));
        }
Пример #57
0
        public void NotContain()
        {
            var notContainValue = JsonValue.Number(int.MinValue);

            _jsonArray.Contains(notContainValue).Should().BeFalse();
        }
Пример #58
0
 private static IJsonValue CreateValue(params string?[]?ids)
 {
     return(ids == null ? JsonValue.Null : JsonValue.Array(ids.OfType <object>().ToArray()));
 }
Пример #59
0
 public static void RenderDebug(JsonValue root)
 {
     root.InputText("Scourge", "scourge");
 }
Пример #60
0
        public static IJsonValue Map(JsValue?value)
        {
            if (value == null || value.IsNull() || value.IsUndefined())
            {
                return(JsonValue.Null);
            }

            if (value.IsString())
            {
                return(JsonValue.Create(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(JsonValue.Create(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(JsonValue.Create(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(JsonValue.Create(value.AsDate().ToString()));
            }

            if (value.IsRegExp())
            {
                return(JsonValue.Create(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var result = JsonValue.Array();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    result.Add(Map(arr.Get(i.ToString())));
                }

                return(result);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var result = JsonValue.Object();

                foreach (var(key, propertyDescriptor) in obj.GetOwnProperties())
                {
                    result[key] = Map(propertyDescriptor.Value);
                }

                return(result);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }