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;
        }
Example #2
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;
        }
Example #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.");
        }
Example #4
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)
		{
			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;
		}
		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;
		}
Example #7
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;
        }
Example #8
0
 public UserMentionEntity(JsonValue json) : base(json)
 {
     Id = json["id"].AsLong();
     ScreenName = json["screen_name"].AsStringOrNull();
     Name = json["name"].AsStringOrNull();
     FullText = DisplayText = "@" + ScreenName;
 }
Example #9
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 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;
        }
 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 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;
 }
 /// <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;
 }
 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;
 }
Example #16
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;
        }
        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;
        }
Example #18
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;
            }
        }
Example #19
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;
        }
Example #20
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--;
        }
Example #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;
 }
Example #22
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}"));
 }
 public object Deserialize(JsonValue value, JsonMapper mapper)
 {
     return new DropboxLink()
     {
         Url = value.GetValue<string>("url"),
         ExpireDate = JsonUtils.ToDropboxDateTime(value.GetValue<string>("expires")).Value
     };
 }
		public Speaker (JsonValue json) : this()
		{
			Id = json["id"];
			Name = json["name"];
			TwitterHandle = json["twitterHandle"];
			Bio = json["bio"];
			HeadshotUrl = json["headshotUrl"];
		}
Example #25
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 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)
 {
     IList<DirectMessage> directMessages = new List<DirectMessage>();
     foreach (JsonValue itemValue in value.GetValues())
     {
         directMessages.Add(mapper.Deserialize<DirectMessage>(itemValue));
     }
     return directMessages;
 }
 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 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<Place> places = new List<Place>();
     foreach (JsonValue itemValue in value.GetValue("result").GetValues("places"))
     {
         places.Add(mapper.Deserialize<Place>(itemValue));
     }
     return places;
 }