예제 #1
0
 public JsonValue ToJson(IJsonContext context) {
     var dict = new JsonDictionary();
     dict["UserName"] = context.ToJson(UserName);
     dict["ValidTo"] = context.ToJson(ValidTo.ToUnixTime());
     dict["ApiToken"] = context.ToJson(ApiToken);
     return dict;
 }
예제 #2
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;
        }
예제 #3
0
파일: Json.cs 프로젝트: aata/szotar
            public JsonValue ToJson(object value, IJsonContext context)
            {
                if (value == null)
                {
                    return(null);
                }

                var c = value as IJsonConvertible;

                if (c != null)
                {
                    return(c.ToJson(context));
                }

                throw new JsonConvertException("There is no converter registered for the type " + type.Namespace + "." + type.Name + " and it does not implement IJsonConvertible");
            }
예제 #4
0
파일: Json.cs 프로젝트: aata/szotar
            public object FromJson(JsonValue json, IJsonContext context)
            {
                var c = type.GetConstructor(
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new[] { typeof(JsonValue), typeof(IJsonContext) },
                    null
                    );

                if (c != null)
                {
                    return(c.Invoke(new object[] { json, context }));
                }

                throw new JsonConvertException("There is no converter registered for the type " + type.Namespace + "." + type.Name + " and it does not have a constructor taking a JsonValue and an IJsonContext");
            }
예제 #5
0
 public JsonValue ToJson(IJsonContext ctx)
 {
     return(new JsonDictionary()
            .Set("items", ctx.ToJson(items))
            .Set("nextItems", ctx.ToJson(nextItems))
            .Set("failed", new JsonBool(failed))
            .Set("currentItem", ctx.ToJson(CurrentItem))
            .Set("currentIndex", new JsonNumber(CurrentIndex))
            .Set("itemCount", new JsonNumber(ItemCount))
            .Set("score", new JsonNumber(Score))
            .Set("round", new JsonNumber(Round))
            .Set("lastRoundInfo", ctx.ToJson(LastRoundInfo))
            .Set("allRounds", ctx.ToJson(AllRounds.ToList()))
            .Set("title", new JsonString(Title))
            .Set("maxItemCount", new JsonNumber(maxItemCount)));
 }
예제 #6
0
        public TermModel(JsonValue json, IJsonContext context) {
            if (json == null)
                throw new ArgumentNullException(nameof(json));
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            var dict = JsonDictionary.FromValue(json);
            TermID = context.FromJson<long>(dict["id"]);
            Term = context.FromJson<string>(dict["term"]);
            Definition = context.FromJson<string>(dict["definition"]);
            if (dict.Items.ContainsKey("image") && dict.Items["image"] is JsonDictionary) {
                var imageDict = dict.GetSubDictionary("image");
                ImageWidth = imageDict.Get<int>("width", context);
                ImageHeight = imageDict.Get<int>("height", context);
            }
        }
예제 #7
0
        public bool CanBuild <T>(IJsonContext context)
        {
            var type = typeof(T);

            if (!IsRequestedTypeSupported(type))
            {
                return(false);
            }
            var delegatingType = GenerateDelegatingType(type);

            if (delegatingType == null)
            {
                return(false);
            }
            return(context.GetSerializatorReflection(delegatingType) != null);
        }
예제 #8
0
        public bool CanBuild <T>(IJsonContext context)
        {
            var type = typeof(T);

            if (!IsRequestedTypeSupported(type))
            {
                return(false);
            }
            var genericTypes = type.GenericTypeArguments;

            if (!CheckGenericTypeArgs(genericTypes))
            {
                return(false);
            }
            return(CheckAllGenericParameters(context, genericTypes));
        }
예제 #9
0
        public override void FromJson(IJsonContext context, IJsonReader reader, out string instance)
        {
            var token = reader.GetNextToken();

            if (token == JsonToken.Null)
            {
                instance = null;
            }
            else if (token == JsonToken.String)
            {
                instance = reader.ReadValue();
            }
            else
            {
                instance = ThrowInvalidJsonException <string>();
            }
        }
예제 #10
0
        public override JsonBoolean FromJson(IJsonContext context, IJsonReader reader)
        {
            switch (reader.GetNextToken())
            {
            case JsonToken.Null:
                return(null);

            case JsonToken.False:
                return(JsonBoolean.False);

            case JsonToken.True:
                return(JsonBoolean.True);

            default:
                return(ExceptionHelper.ThrowInvalidJsonException <JsonBoolean>());
            }
        }
예제 #11
0
        public PracticeViewModel(JsonValue json, IJsonContext ctx)
        {
            var dict = JsonDictionary.FromValue(json);

            items         = ctx.FromJson <List <PracticeItem> >(dict["items"]);
            nextItems     = ctx.FromJson <List <PracticeItem> >(dict["nextItems"]);
            failed        = ctx.FromJson <bool>(dict["failed"]);
            currentItem   = ctx.FromJson <PracticeItem>(dict["currentItem"]);
            currentIndex  = ctx.FromJson <int>(dict["currentIndex"]);
            itemCount     = ctx.FromJson <int>(dict["itemCount"]);
            score         = ctx.FromJson <int>(dict["score"]);
            round         = ctx.FromJson <int>(dict["round"]);
            lastRoundInfo = ctx.FromJson <RoundInfo>(dict["lastRoundInfo"]);
            allRounds     = new ObservableCollection <RoundInfo>(ctx.FromJson <List <RoundInfo> >(dict["allRounds"]));
            maxItemCount  = ctx.FromJson <int>(dict["maxItemCount"]);
            title         = ctx.FromJson <string>(dict["title"]);
        }
예제 #12
0
 public static void Run(IJsonContext ctx)
 {
     ctx.TestString();
     ctx.TestInt();
     ctx.TestIntNullable();
     ctx.TestLong();
     ctx.TestLongNullable();
     ctx.TestGuid();
     ctx.TestGuidNullable();
     ctx.TestChar();
     ctx.TestCharNullable();
     ctx.TestListOfInt();
     ctx.TestListOfListOfString();
     ctx.TestDictionaryOfIntInt();
     ctx.TestDictionaryOfStringInt();
     ctx.TestArray();
 }
예제 #13
0
        public override void FromJson(IJsonContext context, IJsonReader reader, out bool instance)
        {
            switch (reader.GetNextToken())
            {
            case JsonToken.False:
                instance = false;
                break;

            case JsonToken.True:
                instance = true;
                break;

            default:
                instance = ThrowInvalidJsonException <bool>();
                break;
            }
        }
예제 #14
0
파일: Json.cs 프로젝트: aata/szotar
            public JsonValue ToJson(object value, IJsonContext context)
            {
                var list = value as List <T>;

                if (list == null)
                {
                    throw new JsonConvertException("Value was not a List<" + typeof(T) + ">");
                }

                var array = new JsonArray();

                foreach (var item in list)
                {
                    array.Items.Add(context.ToJson(item));
                }

                return(array);
            }
예제 #15
0
파일: ListInfo.cs 프로젝트: aata/szotar
        JsonValue IJsonConvertible.ToJson(IJsonContext context)
        {
            var dict = new JsonDictionary();

            if (ID.HasValue)
            {
                dict.Items.Add("ID", new JsonNumber(ID.Value));
            }
            if (Name != null)
            {
                dict.Items.Add("Name", new JsonString(Name));
            }
            if (Author != null)
            {
                dict.Items.Add("Author", new JsonString(Author));
            }
            if (Language != null)
            {
                dict.Items.Add("Language", new JsonString(Language));
            }
            if (Url != null)
            {
                dict.Items.Add("Url", new JsonString(Url));
            }
            if (Date.HasValue)
            {
                dict.Items.Add("Date", new JsonString(Date.Value.ToString("s")));
            }
            if (TermCount.HasValue)
            {
                dict.Items.Add("TermCount", new JsonNumber(TermCount.Value));
            }
            if (SyncID.HasValue)
            {
                dict.Items.Add("SyncID", new JsonNumber(SyncID.Value));
            }
            if (SyncDate.HasValue)
            {
                dict.Items.Add("SyncDate", new JsonNumber(SyncDate.Value.ToUnixTime()));
            }
            dict.Items.Add("SyncNeeded", new JsonBool(SyncNeeded));

            return(dict);
        }
예제 #16
0
파일: UserModel.cs 프로젝트: aata/szotar
        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;
        }
예제 #17
0
        public UserInfo(JsonValue json, IJsonContext context) : this()
        {
            var dict = json as JsonDictionary;

            if (dict == null)
            {
                throw new JsonConvertException("Expected a JSON dictionary to be converted to a UserInfo");
            }

            bool wasRelaxed = context.RelaxedNumericConversion;

            context.RelaxedNumericConversion = true;

            UserName    = context.FromJson <string>(dict["username"]);
            AccountType = "free";
            SignUpDate  = new DateTime(1970, 1, 1).AddSeconds(context.FromJson <long>(dict["sign_up_date"]));

            Sets   = context.FromJson <List <SetInfo> >(dict["sets"]);
            Groups = context.FromJson <List <GroupInfo> >(dict["groups"]);

            foreach (var k in dict.Items)
            {
                switch (k.Key)
                {
                case "account_type": AccountType = context.FromJson <string>(k.Value); break;

                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;

                case "profile_image": ProfileImage = new Uri(context.FromJson <string>(k.Value), UriKind.Absolute); break;
                }
            }

            context.RelaxedNumericConversion = wasRelaxed;
        }
예제 #18
0
 public void ToJson(IJsonContext context, IJsonWriter writer, TList instance)
 {
     if (instance == null)
     {
         writer.WriteRaw(JsonLiterals.Null);
     }
     else
     {
         writer.WriteRaw(JsonLiterals.ArrayStart);
         if (instance.Count > 0)
         {
             ToJsonItem(context, writer, instance[0]);
             for (int i = 1; i < instance.Count; i++)
             {
                 writer.WriteRaw(JsonLiterals.Comma);
                 ToJsonItem(context, writer, instance[i]);
             }
         }
         writer.WriteRaw(JsonLiterals.ArrayEnd);
     }
 }
예제 #19
0
 public static IJsonSerializator GetSerializatorReflection(this IJsonContext context, Type type)
 {
     try
     {
         MethodInfo generic = GetJsonSerializatorMethod.MakeGenericMethod(type);
         object     result  = generic.Invoke(context, null);
         return((IJsonSerializator)result);
     }
     catch (JsonException exc)
     {
         if (exc.Type == JsonExceptionType.MapperNotRegistered)
         {
             return(null);
         }
         throw;
     }
     catch (Exception exc)
     {
         return(ExceptionHelper.ThrowUnexpectedException <IJsonSerializator>(exc));
     }
 }
예제 #20
0
        public IJsonMapper <T> Build <T>(IJsonContext context)
        {
            var type = typeof(T);

            if (!IsRequestedTypeSupported(type))
            {
                return(null);
            }
            var genericTypes = type.GenericTypeArguments;

            if (!CheckGenericTypeArgs(genericTypes))
            {
                return(null);
            }
            var serializators = GetJsonSerializators(context, genericTypes);

            if (serializators == null)
            {
                return(null);
            }
            return(Build <T>(type, genericTypes, serializators));
        }
예제 #21
0
        private static void TestIntNullable(this IJsonContext ctx)
        {
            var serializator = ctx.GetSerializator <int?>();

            var input1  = (int?)123;
            var json1   = serializator.ToJson(input1);
            var output1 = serializator.FromJson(json1);

            if (input1 != output1)
            {
                throw new Exception("IntNullable test 1 failed...");
            }

            var input2  = (int?)null;
            var json2   = serializator.ToJson(input2);
            var output2 = serializator.FromJson(json2);

            if (input2 != output2)
            {
                throw new Exception("IntNullable test 2 failed...");
            }
        }
예제 #22
0
        private static void TestString(this IJsonContext ctx)
        {
            var serializator = ctx.GetSerializator <string>();

            var input1  = "That is some input string";
            var json1   = serializator.ToJson(input1);
            var output1 = serializator.FromJson(json1);

            if (input1 != output1)
            {
                throw new Exception("String test 1 failed...");
            }

            var input2  = (string)null;
            var json2   = serializator.ToJson(input2);
            var output2 = serializator.FromJson(json2);

            if (input2 != output2)
            {
                throw new Exception("String test 2 failed...");
            }
        }
예제 #23
0
        public IJsonMapper <T> Build <T>(IJsonContext context)
        {
            var type = typeof(T);

            if (!IsRequestedTypeSupported(type))
            {
                return(null);
            }
            var delegatingType = GenerateDelegatingType(type);

            if (delegatingType == null)
            {
                return(null);
            }
            var serializator = context.GetSerializatorReflection(delegatingType);

            if (serializator == null)
            {
                return(null);
            }
            return(Build <T>(type, delegatingType, serializator));
        }
예제 #24
0
파일: SetModel.cs 프로젝트: dbremner/szotar
        public SetModel(JsonValue json, IJsonContext context) {
            var dict = JsonDictionary.FromValue(json);

            SetID = dict.Get<long>("id", context);
            Uri = new Uri(dict.Get<string>("url", context));
            Title = dict.Get<string>("title", context);
            Author = dict.Get<string>("created_by", context);
            Description = dict.Get<string>("description", context, null);
            TermCount = dict.Get<int>("term_count", context);
            Created = new DateTime(1970, 1, 1).AddSeconds(dict.Get<double>("created_date", context));
            Modified = new DateTime(1970, 1, 1).AddSeconds(dict.Get<double>("modified_date", context));
            Subjects = context.FromJson<List<string>>(dict["subjects"]);
            Visibility = SetPermissions.ParseVisibility(dict.Get<string>("visibility", context));
            EditPermissions = SetPermissions.ParseEditPermissions(dict.Get<string>("editable", context));
            HasAccess = dict.Get<bool>("has_access", context);
            HasDiscussion = dict.Get<bool>("has_discussion", context, false);
            TermLanguageCode = dict.Get<string>("lang_terms", context, null);
            DefinitionLanguageCode = dict.Get<string>("lang_definitions", context, null);

            if (dict.Items.ContainsKey("terms"))
                Terms = context.FromJson<List<TermModel>>(dict["terms"]);
        }
예제 #25
0
파일: SetModel.cs 프로젝트: dbremner/szotar
 public JsonValue ToJson(IJsonContext context) {
     var dict = new JsonDictionary();
     dict.Set("id", SetID);
     dict.Set("url", Uri.ToString());
     dict.Set("title", Title);
     dict.Set("created_by", Author);
     if (Description != null)
         dict.Set("description",Description);
     dict.Set("term_count", TermCount);
     dict.Set("created_date", Created.ToUnixTime());
     dict.Set("modified_date", Modified.ToUnixTime());
     dict["subjects"] = context.ToJson(Subjects);
     dict.Set("visibility", Visibility.ToApiString());
     dict.Set("editable", EditPermissions.ToApiString());
     dict.Set("has_access", HasAccess);
     dict.Set("has_discussion", HasDiscussion);
     dict.Set("lang_terms", TermLanguageCode);
     dict.Set("lang_definitions", DefinitionLanguageCode);
     if (Terms != null)
         dict["terms"] = context.ToJson(Terms);
     return dict;
 }
예제 #26
0
        public TClass FromJson(IJsonContext context, IJsonReader reader)
        {
            var token = reader.GetNextToken();

            if (token == JsonToken.Null)
            {
                return(default(TClass));
            }
            if (token == JsonToken.ObjectEmpty)
            {
                return(_instanceProvider());
            }
            if (token != JsonToken.ObjectStart)
            {
                return(ExceptionHelper.ThrowInvalidJsonException <TClass>());
            }
            var result = _instanceProvider();

            while (true)
            {
                token = reader.GetNextToken();
                if (token == JsonToken.ObjectEnd)
                {
                    break;
                }
                if (token != JsonToken.Comma)
                {
                    reader.RepeatLastToken();
                }
                JsonContextHelper.ThrowIfNotMatch(reader, JsonToken.String);
                var key = reader.ReadValue();
                JsonContextHelper.ThrowIfNotMatch(reader, JsonToken.Colon);
                if (_setters.TryGetValue(key, out IJsonGetterSetter <TClass> setter))
                {
                    setter.FromJson(context, reader, result);
                }
            }
            return(result);
        }
예제 #27
0
        public override JsonObject FromJson(IJsonContext context, IJsonReader reader)
        {
            var token = reader.GetNextToken();

            if (token == JsonToken.Null)
            {
                return(null);
            }
            if (token == JsonToken.ObjectEmpty)
            {
                return(new JsonObject());
            }
            if (token != JsonToken.ObjectStart)
            {
                return(ExceptionHelper.ThrowInvalidJsonException <JsonObject>());
            }

            var result = new JsonObject();

            while (true)
            {
                token = reader.GetNextToken();
                if (token == JsonToken.ObjectEnd)
                {
                    break;
                }
                if (token != JsonToken.Comma)
                {
                    reader.RepeatLastToken();
                }
                JsonContextHelper.ThrowIfNotMatch(reader, JsonToken.String);
                var key = reader.ReadValue();
                JsonContextHelper.ThrowIfNotMatch(reader, JsonToken.Colon);
                var value = JsonElementMapper.FromJson(context, reader);
                result.GetObjectMembers().Add(key, value);
            }
            return(result);
        }
예제 #28
0
        public GroupInfo(JsonValue json, IJsonContext context)
            : this()
        {
            var dict = json as JsonDictionary;
            if (dict == null)
                throw new JsonConvertException("Expected a JSON dictionary to be converted to a GroupInfo");

            bool wasRelaxed = context.RelaxedNumericConversion;
            context.RelaxedNumericConversion = true;
            bool hasID = false, hasName = false;

            foreach (var item in dict.Items) {
                switch (item.Key) {
                    case "id":
                        hasID = true;
                        ID = context.FromJson<long>(item.Value);
                        break;
                    case "name":
                        hasName = true;
                        Name = context.FromJson<string>(item.Value);
                        break;
                    case "description": Description = context.FromJson<string>(item.Value); break;
                    case "user_count": UserCount = context.FromJson<int>(item.Value); break;
                    case "created_date": Created = new DateTime(context.FromJson<long>(item.Value)); break;
                    case "is_public": IsPublic = context.FromJson<bool>(item.Value); break;
                    case "has_password": HasPassword = context.FromJson<bool>(item.Value); break;
                    case "has_access": HasAccess = context.FromJson<bool>(item.Value); break;
                    case "has_discussion": HasDiscussion = context.FromJson<bool>(item.Value); break;
                    case "member_add_sets": MemberAddSets = context.FromJson<bool>(item.Value); break;
                    case "sets": Sets = context.FromJson<List<SetInfo>>(item.Value); break;
                }
            }

            if (!hasID || !hasName)
                throw new JsonConvertException("Server did not supply group ID or name");

            context.RelaxedNumericConversion = wasRelaxed;
        }
예제 #29
0
        protected MruList(JsonValue json, IJsonContext context)
        {
            var dict = json as JsonDictionary;

            if (dict == null)
            {
                throw new JsonConvertException("Expected a JSON dictionary");
            }

            foreach (var k in dict.Items)
            {
                switch (k.Key)
                {
                case "Entries":
                    Entries = context.FromJson <List <T> >(k.Value);
                    break;

                case "MaximumSize":
                    MaximumSize = context.FromJson <int>(k.Value);
                    break;
                }
            }
        }
예제 #30
0
        JsonValue IJsonConvertible.ToJson(IJsonContext context)
        {
            var dict = new JsonDictionary();

            if (Name != null)
            {
                dict.Items.Add("Name", new JsonString(Name));
            }
            if (Author != null)
            {
                dict.Items.Add("Author", new JsonString(Author));
            }
            if (Path != null)
            {
                dict.Items.Add("Path", new JsonString(Path));
            }
            if (Url != null)
            {
                dict.Items.Add("Url", new JsonString(Url));
            }

            return(dict);
        }
예제 #31
0
        public TermModel(JsonValue json, IJsonContext context)
        {
            if (json == null)
            {
                throw new ArgumentNullException("json");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var dict = JsonDictionary.FromValue(json);

            TermID     = context.FromJson <long>(dict["id"]);
            Term       = context.FromJson <string>(dict["term"]);
            Definition = context.FromJson <string>(dict["definition"]);
            if (dict.Items.ContainsKey("image") && dict.Items["image"] is JsonDictionary)
            {
                var imageDict = dict.GetSubDictionary("image");
                ImageWidth  = imageDict.Get <int>("width", context);
                ImageHeight = imageDict.Get <int>("height", context);
            }
        }
예제 #32
0
        public override JsonElement FromJson(IJsonContext context, IJsonReader reader)
        {
            switch (reader.GetNextToken())
            {
            case JsonToken.ObjectStart:
                reader.RepeatLastToken();
                return(JsonObjectMapper.FromJson(context, reader));

            case JsonToken.String:
                return(new JsonString(reader.ReadValue()));

            case JsonToken.False:
                return(JsonBoolean.False);

            case JsonToken.True:
                return(JsonBoolean.True);

            case JsonToken.Null:
                return(JsonNull.Null);

            case JsonToken.Number:
                return(JsonNull.Null);

            case JsonToken.ArrayStart:
                reader.RepeatLastToken();
                return(JsonArrayMapper.FromJson(context, reader));

            case JsonToken.ObjectEmpty:
                return(new JsonObject());

            case JsonToken.ArrayEmpty:
                return(new JsonArray());

            default:
                return(ExceptionHelper.ThrowInvalidJsonException <JsonElement>());
            }
        }
예제 #33
0
 internal override void ToJson(
     IJsonContext context, IJsonWriter writer, IJsonMapper <JsonElement> elMapper)
 {
     writer.WriteRaw(JsonLiterals.ObjectStart);
     if (_objectMembers.Count > 0)
     {
         var addComma = false;
         foreach (var member in _objectMembers)
         {
             if (addComma)
             {
                 writer.WriteRaw(JsonLiterals.Comma);
             }
             else
             {
                 addComma = true;
             }
             writer.WriteRaw(member.Key.EncodeToJsonString());
             writer.WriteRaw(JsonLiterals.Colon);
             elMapper.ToJson(context, writer, member.Value);
         }
     }
     writer.WriteRaw(JsonLiterals.ObjectEnd);
 }
예제 #34
0
 public PracticeViewModel(JsonValue json, IJsonContext ctx)
 {
     var dict = JsonDictionary.FromValue(json);
     items = ctx.FromJson<List<PracticeItem>>(dict["items"]);
     nextItems = ctx.FromJson<List<PracticeItem>>(dict["nextItems"]);
     failed = ctx.FromJson<bool>(dict["failed"]);
     currentItem = ctx.FromJson<PracticeItem>(dict["currentItem"]);
     currentIndex = ctx.FromJson<int>(dict["currentIndex"]);
     itemCount = ctx.FromJson<int>(dict["itemCount"]);
     score = ctx.FromJson<int>(dict["score"]);
     round = ctx.FromJson<int>(dict["round"]);
     lastRoundInfo = ctx.FromJson<RoundInfo>(dict["lastRoundInfo"]);
     allRounds = new ObservableCollection<RoundInfo>(ctx.FromJson<List<RoundInfo>>(dict["allRounds"]));
     maxItemCount = ctx.FromJson<int>(dict["maxItemCount"]);
     title = ctx.FromJson<string>(dict["title"]);
 }
예제 #35
0
 public JsonValue ToJson(IJsonContext context)
 {
     throw new NotImplementedException();
 }
예제 #36
0
 public PracticeItem(JsonValue json, IJsonContext ctx)
 {
     var dict = JsonDictionary.FromValue(json);
     term = ctx.FromJson<string>(dict["term"]);
     definition  = ctx.FromJson<string>(dict["definition"]);
 }
예제 #37
0
 public JsonValue ToJson(IJsonContext ctx)
 {
     return new JsonDictionary()
         .Set("items", ctx.ToJson(items))
         .Set("nextItems", ctx.ToJson(nextItems))
         .Set("failed", new JsonBool(failed))
         .Set("currentItem", ctx.ToJson(CurrentItem))
         .Set("currentIndex", new JsonNumber(CurrentIndex))
         .Set("itemCount", new JsonNumber(ItemCount))
         .Set("score", new JsonNumber(Score))
         .Set("round", new JsonNumber(Round))
         .Set("lastRoundInfo", ctx.ToJson(LastRoundInfo))
         .Set("allRounds", ctx.ToJson(AllRounds.ToList()))
         .Set("title", new JsonString(Title))
         .Set("maxItemCount", new JsonNumber(maxItemCount));
 }
예제 #38
0
 public RoundInfo(JsonValue json, IJsonContext ctx)
 {
     var dict = JsonDictionary.FromValue(json);
     RoundNumber = ctx.FromJson<int>(dict["roundNumber"]);
     Score = ctx.FromJson<int>(dict["score"]);
     ItemCount = ctx.FromJson<int>(dict["itemCount"]);
 }
예제 #39
0
 public JsonValue ToJson(IJsonContext context)
 {
     return new JsonDictionary()
         .Set("roundNumber", new JsonNumber(RoundNumber))
         .Set("score", new JsonNumber(Score))
         .Set("itemCount", new JsonNumber(ItemCount));
 }
예제 #40
0
 public JsonValue ToJson(IJsonContext context)
 {
     return new JsonDictionary()
         .Set("term", term)
         .Set("definition", definition);
 }
예제 #41
0
파일: ListInfo.cs 프로젝트: aata/szotar
        protected ListInfo(JsonValue value, IJsonContext context)
        {
            var dict = value as JsonDictionary;

            if (dict == null)
            {
                throw new JsonConvertException("Value was not a dictionary");
            }

            foreach (var k in dict.Items)
            {
                switch (k.Key)
                {
                case "ID":
                    if (k.Value != null)
                    {
                        var n = k.Value as JsonNumber;
                        if (n == null)
                        {
                            throw new JsonConvertException("ListInfo.ID was not a number");
                        }

                        ID = n.LongValue;
                    }
                    break;

                case "Name":
                case "Author":
                case "Language":
                case "Url":
                    if (k.Value != null)
                    {
                        var s = k.Value as JsonString;
                        if (s == null)
                        {
                            throw new JsonConvertException("ListInfo." + k.Key + " was not a number");
                        }

                        SetStringProperty(k.Key, s.Value);
                    }
                    break;

                case "Date":
                    if (k.Value != null)
                    {
                        var s = k.Value as JsonString;
                        if (s == null)
                        {
                            throw new JsonConvertException("ListInfo.Date was not a string");
                        }

                        Date = DateTime.Parse(s.Value);
                    }
                    break;

                case "TermCount":
                    if (k.Value != null)
                    {
                        var n = k.Value as JsonNumber;
                        if (n == null)
                        {
                            throw new JsonConvertException("ListInfo.TermCount was not a number");
                        }

                        TermCount = n.LongValue;
                    }
                    break;

                case "SyncID":
                    SyncID = context.FromJson <long>(k.Value);
                    break;

                case "SyncDate":
                    SyncDate = context.FromJson <long>(k.Value).DateTimeFromUnixTime();
                    break;

                case "SyncNeeded":
                    SyncNeeded = context.FromJson <bool>(k.Value);
                    break;
                }
            }
        }
예제 #42
0
 public GroupModel(JsonValue json, IJsonContext context) {
 }
예제 #43
0
        public UserInfo(JsonValue json, IJsonContext context)
            : this()
        {
            var dict = json as JsonDictionary;
            if (dict == null)
                throw new JsonConvertException("Expected a JSON dictionary to be converted to a UserInfo");

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

            UserName = context.FromJson<string>(dict["username"]);
            AccountType = "free";
            SignUpDate = new DateTime(1970, 1, 1).AddSeconds(context.FromJson<long>(dict["sign_up_date"]));

            Sets = context.FromJson<List<SetInfo>>(dict["sets"]);
            Groups = context.FromJson<List<GroupInfo>>(dict["groups"]);

            foreach (var k in dict.Items) {
                switch (k.Key) {
                    case "account_type": AccountType = context.FromJson<string>(k.Value); break;
                    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;
                    case "profile_image": ProfileImage = new Uri(context.FromJson<string>(k.Value), UriKind.Absolute); break;
                }
            }

            context.RelaxedNumericConversion = wasRelaxed;
        }
예제 #44
0
 public JsonValue ToJson(IJsonContext context)
 {
     throw new NotImplementedException();
 }
예제 #45
0
        public Set(JsonValue json, IJsonContext context)
            : this()
        {
            var dict = json as JsonDictionary;
            if (dict == null)
                throw new JsonConvertException("Expected a JSON dictionary to be converted to a SetInfo");

            if (!dict.Items.ContainsKey("id"))
                throw new JsonConvertException("Expected SetInfo JSON to contain an 'id' property");

            foreach (var k in dict.Items) {
                switch (k.Key) {
                    case "id": ID = context.FromJson<long>(k.Value); break;
                    case "url": Uri = context.FromJson<string>(k.Value); break;
                    case "title": Title = context.FromJson<string>(k.Value); break;
                    case "created_by": Author = context.FromJson<string>(k.Value); break;
                    case "description": Description = context.FromJson<string>(k.Value); break;
                    case "term_count": TermCount = context.FromJson<int>(k.Value); break;
                    case "created_date": Created = new DateTime(1970, 1, 1).AddSeconds(context.FromJson<long>(k.Value)); break;
                    case "modified_date": Modified = new DateTime(1970, 1, 1).AddSeconds(context.FromJson<long>(k.Value)); break;
                    case "subjects": AddSubjects(context.FromJson<List<string>>(k.Value)); break;
                    case "visibility": Visibility = SetPermissions.ParseVisibility(context.FromJson<string>(k.Value)); break;
                    case "editable": Editable = SetPermissions.ParseEditPermissions(context.FromJson<string>(k.Value)); break;
                    case "has_access": HasAccess = context.FromJson<bool>(k.Value); break;
                    case "has_discussion": HasDiscussion = context.FromJson<bool>(k.Value); break;
                    case "lang_terms": TermLanguageCode = context.FromJson<string>(k.Value); break;
                    case "lang_definitions": DefinitionLanguageCode = context.FromJson<string>(k.Value); break;
                    case "terms":
                        var list = new List<Term>();
                        if (k.Value is JsonArray) {
                            foreach (var termJson in ((JsonArray)k.Value).Items) {
                                if (!(termJson is JsonDictionary))
                                    throw new JsonConvertException("Expected SetInfo.Terms to be an array of JSON dictionaries");
                                var term = new Term {
                                    ID = context.FromJson<long>(((JsonDictionary)termJson).Items["id"]),
                                    TermValue = context.FromJson<string>(((JsonDictionary)termJson).Items["term"]),
                                    Definition = context.FromJson<string>(((JsonDictionary)termJson).Items["definition"])
                                };
                                if (term.TermValue == null || term.Definition == null)
                                    throw new JsonConvertException("Either term or definition was not group when converting from JSON to Set");
                                list.Add(term);
                            }
                        } else {
                            throw new JsonConvertException("Expected SetInfo.Terms to be an array");
                        }
                        AddTerms(list);
                        break;
                }
            }

            // TODO: Validate that important fields are defined
        }
예제 #46
0
 public Credentials(JsonValue json, IJsonContext context) : this() {
     var dict = JsonDictionary.FromValue(json);
     UserName = dict.Get<string>("UserName", context);
     ValidTo = dict.Get<long>("ValidTo", context).DateTimeFromUnixTime();
     ApiToken = dict.Get<string>("ApiToken", context);
 }
예제 #47
0
 public override void ToJson(IJsonContext context, IJsonWriter writer, ushort instance)
 {
     writer.WriteRaw(instance.ToString(DefaultCultureInfo));
 }
예제 #48
0
파일: ListInfo.cs 프로젝트: dbremner/szotar
		protected ListInfo(JsonValue value, IJsonContext context) {
			var dict = value as JsonDictionary;
			if (dict == null)
				throw new JsonConvertException("Value was not a dictionary");

			foreach (var k in dict.Items) {
				switch (k.Key) {
					case "ID":
						if (k.Value != null) {
							var n = k.Value as JsonNumber;
							if (n == null)
								throw new JsonConvertException("ListInfo.ID was not a number");
							
							ID = n.LongValue;
						}
						break;

					case "Name":
					case "Author":
					case "Language":
					case "Url":
						if (k.Value != null) {
							var s = k.Value as JsonString;
							if (s == null)
								throw new JsonConvertException("ListInfo." + k.Key + " was not a number");
							
							SetStringProperty(k.Key, s.Value);
						}
						break;

					case "Date":
						if (k.Value != null) {
							var s = k.Value as JsonString;
							if (s == null)
								throw new JsonConvertException("ListInfo.Date was not a string");
							
							Date = DateTime.Parse(s.Value);
						}
						break;

					case "TermCount":
						if (k.Value != null) {
							var n = k.Value as JsonNumber;
							if (n == null)
								throw new JsonConvertException("ListInfo.TermCount was not a number");
							
							TermCount = n.LongValue;
						}
						break;

					case "SyncID":
						SyncID = context.FromJson<long>(k.Value);
						break;

					case "SyncDate":
						SyncDate = context.FromJson<long>(k.Value).DateTimeFromUnixTime();
						break;

					case "SyncNeeded":
						SyncNeeded = context.FromJson<bool>(k.Value);
						break;
				}
			}
		}
예제 #49
0
 public JsonValue ToJson(IJsonContext context) {
     return new JsonDictionary();
 }
예제 #50
0
파일: ListInfo.cs 프로젝트: dbremner/szotar
		JsonValue IJsonConvertible.ToJson(IJsonContext context) {
			var dict = new JsonDictionary();

			if (ID.HasValue)
				dict.Items.Add("ID", new JsonNumber(ID.Value));
			if (Name != null)
				dict.Items.Add("Name", new JsonString(Name));
			if (Author != null)
				dict.Items.Add("Author", new JsonString(Author));
			if (Language != null)
				dict.Items.Add("Language", new JsonString(Language));
			if (Url != null)
				dict.Items.Add("Url", new JsonString(Url));
			if (Date.HasValue)
				dict.Items.Add("Date", new JsonString(Date.Value.ToString("s")));
			if (TermCount.HasValue)
				dict.Items.Add("TermCount", new JsonNumber(TermCount.Value));
			if (SyncID.HasValue)
				dict.Items.Add("SyncID", new JsonNumber(SyncID.Value));
			if (SyncDate.HasValue)
				dict.Items.Add("SyncDate", new JsonNumber(SyncDate.Value.ToUnixTime()));
			dict.Items.Add("SyncNeeded", new JsonBool(SyncNeeded));

			return dict;
		}