Exemple #1
0
        public static DTO.QueryComposer.QueryComposerResponseDTO DeserializeResponse(string json)
        {
            Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json.Trim());

            var serializationSettings = new Newtonsoft.Json.JsonSerializerSettings();

            serializationSettings.Converters.Add(new DTO.QueryComposer.QueryComposerResponsePropertyDefinitionConverter());
            serializationSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.IgnoreAndPopulate;
            Newtonsoft.Json.JsonSerializer serializer = Newtonsoft.Json.JsonSerializer.Create(serializationSettings);

            if (obj.ContainsKey("SchemaVersion"))
            {
                return(obj.ToObject <DTO.QueryComposer.QueryComposerResponseDTO>(serializer));
            }

            var queryResponse = obj.ToObject <DTO.QueryComposer.QueryComposerResponseQueryResultDTO>(serializer);

            var response = new DTO.QueryComposer.QueryComposerResponseDTO
            {
                Header = new QueryComposerResponseHeaderDTO {
                    ID = queryResponse.ID,
                },
                Errors  = Enumerable.Empty <QueryComposerResponseErrorDTO>(),
                Queries = new[] { queryResponse }
            };

            response.RefreshQueryDates();
            response.RefreshErrors();

            return(response);
        }
        public async Task <IActionResult> ChangeUserStatus(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            ApplicationUser user = await dbContext.ApplicationUsers.FirstOrDefaultAsync(u => u.Id == id);

            if (user == null)
            {
                return(NotFound(new { Code = "404", Message = "Not Found" }));
            }
            else
            {
                Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

                if (payload.SelectToken("userStatus") != null &&
                    payload.SelectToken("userStatus").ToString() != string.Empty)
                {
                    string Status = payload.SelectToken("userStatus").ToObject <string>();
                    user.userStatus = Status;
                    dbContext.ApplicationUsers.Update(user);
                }
            }

            var result = await dbContext.SaveChangesAsync();

            if (result > 0)
            {
                return(Ok(new { Code = "200", Message = "User Status Changed" }));
            }
            else
            {
                return(BadRequest(new { Code = "400", Message = "UserStatus field is required" }));
            }
        }
Exemple #3
0
        public T GetJson <T>(string filename)
        {
            string  filepath = Path.Combine(this.pathPrefix, filename);
            JObject jObject  = JObject.Parse(File.ReadAllText(filepath));

            T thing = jObject.ToObject <T>();

            List <string> nullProperties =
                GetNullProperties(thing.GetType().FullName, thing).ToList();

            if (nullProperties.Any())
            {
                string message = System.String.Join("\n", nullProperties
                                                    .Select(str => "\t- " + str)
                                                    .Prepend("\nThese properties are missing from '" + filename + "':"));

                if (throwExceptionOnInvalidJson)
                {
                    throw new InvalidJsonException(message);
                }
                else
                {
                    System.Console.WriteLine(message);
                }
            }

            return(thing);
        }
Exemple #4
0
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext ctx)
        {
            _logger.LogDebug("Selected PHP version: {phpVer}", ctx.PhpVersion);
            bool composerFileExists = false;

            if (ctx.SourceRepo.FileExists(PhpConstants.ComposerFileName))
            {
                composerFileExists = true;

                try
                {
                    dynamic composerFile = ctx.SourceRepo.ReadJsonObjectFromFile(PhpConstants.ComposerFileName);
                    if (composerFile?.require != null)
                    {
                        Newtonsoft.Json.Linq.JObject deps = composerFile?.require;
                        var depSpecs = deps.ToObject<IDictionary<string, string>>();
                        _logger.LogDependencies(this.Name, ctx.PhpVersion, depSpecs.Select(kv => kv.Key + kv.Value));
                    }
                }
                catch (Exception exc)
                {
                    // Leave malformed composer.json files for Composer to handle.
                    // This prevents Oryx from erroring out when Composer itself might be able to tolerate the file.
                    _logger.LogWarning(exc, $"Exception caught while trying to deserialize {PhpConstants.ComposerFileName}");
                }
            }

            var props = new PhpBashBuildSnippetProperties { ComposerFileExists = composerFileExists };
            string snippet = TemplateHelpers.Render(TemplateHelpers.TemplateResource.PhpBuildSnippet, props, _logger);
            return new BuildScriptSnippet { BashBuildScriptSnippet = snippet };
        }
Exemple #5
0
        /// <summary>
        /// UserLogin
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static UserObject UserLogin(string usercode, string pwd)
        {
            UserObject userObj        = null;
            string     responseResult = "";
            HttpResponseResultObject <object> responseObj = null;

            try
            {
                IRMSApiReqParam apiParam = CreateIRMSApiReqParam.CreateUserLoginParam(usercode, pwd);
                if (apiParam != null)
                {
                    responseResult = HttpService.Post(apiParam.JsonData, apiParam.Path, 6000);
                    responseObj    = JsonConvert.DeserializeObject <HttpResponseResultObject <object> >(responseResult);
                    if (responseObj != null && responseObj.Code == SuccessCode)
                    {
                        Newtonsoft.Json.Linq.JObject jObj = responseObj.Data as Newtonsoft.Json.Linq.JObject;
                        if (jObj != null)
                        {
                            userObj = jObj.ToObject <UserObject>();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                userObj = null;
                WindowUI.NlogHelper.LogToFile(ex.ToString());
            }
            //
            return(userObj);
        }
        /// <summary>
        /// Returns the parent item ID
        /// </summary>
        /// <param name="cContext"></param>
        /// <param name="ItemName"></param>
        /// <param name="logger">diagnostics logger</param>
        /// <returns></returns>
        static int GetUserID(ClientContext cContext, dynamic ItemName, ITraceLogger logger)
        {
            int nReturn = -1;
            NativeFieldUserValue userValue = null;

            try
            {
                string itemJsonString = ItemName.ToString();
                Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(itemJsonString);
                userValue = jobject.ToObject <NativeFieldUserValue>();


                logger.LogInformation("Start GetUserID {0}", userValue.Email);
                Web wWeb  = cContext.Web;
                var iUser = cContext.Web.EnsureUser(userValue.Email);
                cContext.Load(iUser);
                cContext.ExecuteQueryRetry();
                if (iUser != null)
                {
                    return(iUser.Id);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to find {0} in web {1}", ItemName, ex.Message);
            }

            return(nReturn);
        }
Exemple #7
0
        public ZaloProfile GetProfile(string code)
        {
            Newtonsoft.Json.Linq.JObject token = appClient.getAccessToken(code);
            var sc = token.GetValue("access_token");

            Newtonsoft.Json.Linq.JObject profile = appClient.getProfile(sc.ToString(), "id,name");
            return(profile.ToObject <ZaloProfile>());
        }
        public void SaveAnnocMessage(Newtonsoft.Json.Linq.JObject msinfo)
        {
            Announcement messageSchedule = msinfo.ToObject <Announcement>();

            using (Imessages ce = new messageRepository())
            {
                ce.SaveMessageFrAnnouncment(messageSchedule);
            }
        }
        public override ProviderCredentials ParseCredentials(Newtonsoft.Json.Linq.JObject serialized)
        {
            if (serialized == null)
            {
                throw new ArgumentNullException("serialized");
            }

            return(serialized.ToObject <CustomLoginProviderCredentials>());
        }
Exemple #10
0
        public Settings readConfig()
        {
            string jsonString = File.ReadAllText("./Settings/60.json");

            Newtonsoft.Json.Linq.JObject json = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(jsonString);
            Settings settings = json.ToObject <Settings>();

            return(settings);
        }
        public Messages saveUserMessage(Newtonsoft.Json.Linq.JObject msfinfo)
        {
            Messages messageSchedule = msfinfo.ToObject <Messages>();

            using (Imessages ce = new messageRepository())
            {
                return(ce.SaveMessage(messageSchedule));
            }
        }
Exemple #12
0
        private object GetObjectFromJObject(object jObject, string entityTypeName)
        {
            Newtonsoft.Json.Linq.JObject jsonObject = jObject as Newtonsoft.Json.Linq.JObject;

            var    entityAssembly = Assembly.GetAssembly(typeof(EntityFramework.WebDbPoliticsModel));
            Type   entityType     = entityAssembly.GetTypes().FirstOrDefault(t => t.Name == entityTypeName);
            object modelObject    = jsonObject.ToObject(entityType);

            return(modelObject);
        }
Exemple #13
0
        internal static NIMIMMessage CreateMessage(Newtonsoft.Json.Linq.JObject token)
        {
            if (!token.HasValues || token.Type != Newtonsoft.Json.Linq.JTokenType.Object)
            {
                return(null);
            }
            var msgTypeToken = token.SelectToken(NIMIMMessage.MessageTypePath);

            if (msgTypeToken == null)
            {
                throw new ArgumentException("message type must be seted:" + token.ToString(Formatting.None));
            }
            var          msgType = msgTypeToken.ToObject <NIMMessageType>();
            NIMIMMessage message = null;

            ConvertAttachStringToObject(token);
            switch (msgType)
            {
            case NIMMessageType.kNIMMessageTypeAudio:
                message = token.ToObject <NIMTextMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeFile:
                message = token.ToObject <NIMFileMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeImage:
                message = token.ToObject <NIMImageMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeLocation:
                message = token.ToObject <NIMLocationMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeText:
                message = token.ToObject <NIMTextMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeVideo:
                message = token.ToObject <NIMVedioMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeNotification:
                message = token.ToObject <NIMTeamNotificationMessage>();
                break;

            default:
                message = token.ToObject <NIMUnknownMessage>();
                (message as NIMUnknownMessage).RawMessage = token.ToString(Formatting.None);
                break;
            }
            return(message);
        }
Exemple #14
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext ctx,
            PlatformDetectorResult detectorResult)
        {
            var phpPlatformDetectorResult = detectorResult as PhpPlatformDetectorResult;

            if (phpPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(PhpPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var buildProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            buildProperties[ManifestFilePropertyKeys.PhpVersion] = phpPlatformDetectorResult.PlatformVersion;

            this.logger.LogDebug("Selected PHP version: {phpVer}", phpPlatformDetectorResult.PlatformVersion);
            bool composerFileExists = false;

            if (ctx.SourceRepo.FileExists(PhpConstants.ComposerFileName))
            {
                composerFileExists = true;

                try
                {
                    dynamic composerFile = ctx.SourceRepo.ReadJsonObjectFromFile(PhpConstants.ComposerFileName);
                    if (composerFile?.require != null)
                    {
                        Newtonsoft.Json.Linq.JObject deps = composerFile?.require;
                        var depSpecs = deps.ToObject <IDictionary <string, string> >();
                        this.logger.LogDependencies(
                            this.Name,
                            phpPlatformDetectorResult.PlatformVersion,
                            depSpecs.Select(kv => kv.Key + kv.Value));
                    }
                }
                catch (Exception exc)
                {
                    // Leave malformed composer.json files for Composer to handle.
                    // This prevents Oryx from erroring out when Composer itself might be able to tolerate the file.
                    this.logger.LogWarning(exc, $"Exception caught while trying to deserialize {PhpConstants.ComposerFileName.Hash()}");
                }
            }

            var props = new PhpBashBuildSnippetProperties {
                ComposerFileExists = composerFileExists
            };
            string snippet = TemplateHelper.Render(TemplateHelper.TemplateResource.PhpBuildSnippet, props, this.logger);

            return(new BuildScriptSnippet {
                BashBuildScriptSnippet = snippet, BuildProperties = buildProperties
            });
        }
        public async Task <ActionResult> EditUser(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

            var account = await userManager.FindByIdAsync(id.ToString());

            if (account != null)
            {
                List <string> errors = ValidateResponseMessagesList(payload);

                if (errors.Count == 0)
                {
                    account.UserName   = payload.SelectToken("userName").ToObject <string>();
                    account.firstName  = payload.SelectToken("firstName").ToObject <string>();
                    account.department = payload.SelectToken("department").ToObject <string>();
                    account.Email      = payload.SelectToken("email").ToObject <string>();
                    account.lastName   = payload.SelectToken("lastName").ToObject <string>();
                    account.middleName = payload.SelectToken("middleName").ToObject <string>();
                    account.rank       = Convert.ToInt32(payload.SelectToken("rank").ToObject <Int32>());
                    account.userType   = payload.SelectToken("userType").ToObject <string>();
                    account.userStatus = payload.SelectToken("userStatus").ToObject <string>();

                    dbContext.Update(account);
                    await dbContext.SaveChangesAsync();
                }
                else
                {
                    return(BadRequest(new ResponseMessage()
                    {
                        Code = "404",
                        Message = errors
                    }));
                }
            }
            else
            {
                return(BadRequest(ResponseMessage = new ResponseMessage {
                    Code = "400",
                    Message = new List <string>()
                    {
                        "Not found"
                    }
                }));
            }

            return(Json(new
            {
                Id = account.Id, UserName = account.UserName,
                firstName = account.firstName, lastName = account.lastName, department = account.department,
                Email = account.Email, middleName = account.middleName,
                rank = account.rank, userType = account.userType,
                DateAcctCreated = account.DateAcctCreated.ToString("MM/dd/yyyy HH:mm")
            }));
        }
Exemple #16
0
        public static bool LoadJsonFile(string filePath, out JsonCharacter jsonCharacter)
        {
            if (File.Exists(filePath) == false)
            {
                jsonCharacter = new JsonCharacter();
                return(false);
            }

            //파일을 읽어서 Json string 생성
            string jsonString = System.IO.File.ReadAllText(filePath);

            try
            {
                //Json object로 생성
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonString);
                //Json object를 JsonCharacter 객체로 형변환 후 Instance로 설정
                jsonCharacter = jObject.ToObject(typeof(JsonCharacter)) as JsonCharacter;
            }
            catch (Exception exception)
            {
                throw exception;
            }

            jsonCharacter.rootPath = KeywordPathManager.GetOriginalPath(jsonCharacter.rootPath);

            for (int i = 0; i < jsonCharacter.characterList.Count(); i++)
            {
                //부모-자식관계 설정
                jsonCharacter.characterList[i].SetParentJsonCharacter(jsonCharacter);

                string imageFilePath = $@"{jsonCharacter.rootPath}\{jsonCharacter.characterList[i].imageFileName}";
                if (File.Exists(imageFilePath))
                {
                    //File lock이 되므로 코드 변경함.
                    //jsonCharacter.characterList[i].image = Image.FromFile(imageFilePath);
                    using (FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
                    {
                        Image loadImage = Image.FromStream(fileStream);
                        jsonCharacter.characterList[i].image = loadImage.Clone() as Image;
                        loadImage.Dispose();
                        fileStream.Close();
                    }
                }
                else
                {
                    jsonCharacter.characterList[i].image = Properties.Resources.DefaultImageBitmap.Clone() as Image;
                }
            }

            //창 닫기 전에 변경사항 확인용 원본 저장
            jsonCharacter.originalJsonString = jsonCharacter.ConvertJsonString();

            return(true);
        }
        public async Task <ActionResult> Create([Bind(Include = "City,Created,Description,FirstName,ImageUri,IsEmergency,LastModified,LastName,OutageType,PhoneNumber,Resolved,State,Street,ZipCode")] IncidentViewModel incident, HttpPostedFileBase imageFile)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Incident incidentToSave = IncidentMapper.MapIncidentViewModel(incident);

                    using (IncidentAPIClient client = IncidentApiHelper.GetIncidentAPIClient())
                    {
                        var result = client.IncidentOperations.CreateIncident(incidentToSave);
                        Newtonsoft.Json.Linq.JObject jobj = (Newtonsoft.Json.Linq.JObject)result;
                        incidentToSave = jobj.ToObject <Incident>();
                    }

                    //TODO: ADD CODE TO UPLOAD THE BLOB
                    //Now upload the file if there is one
                    if (imageFile != null && imageFile.ContentLength > 0)
                    {
                        //### Add Blob Upload code here #####
                        //Give the image a unique name based on the incident id
                        var imageUrl = await StorageHelper.UploadFileToBlobStorage(incidentToSave.Id, imageFile);

                        //### Add Blob Upload code here #####


                        //### Add Queue code here #####
                        //Add a message to the queue to process this image
                        await StorageHelper.AddMessageToQueue(incidentToSave.Id, imageFile.FileName);

                        //### Add Queue code here #####
                    }

                    ////##### CLEAR CACHE ####
                    //RedisCacheHelper.ClearCache(Settings.REDISCCACHE_KEY_INCIDENTDATA);
                    //##### CLEAR CACHE ####
                    //##### SEND EMAIL #####
                    await SendIncidentEmail(incidentToSave);

                    //##### SEND EMAIL  #####

                    await CreateEvent(incidentToSave);


                    return(RedirectToAction("Index", "Dashboard"));
                }
            }
            catch
            {
                return(View());
            }

            return(View(incident));
        }
        public TblProposals CreateProposal([FromBody] Newtonsoft.Json.Linq.JObject json_proposal)
        {
            TblProposals proposal = json_proposal.ToObject <TblProposals>();

            proposal.Id = 0;
            var __newProposal = UnitOfWork.Repository <DevelopersHub.Models.TblProposals>().Add(proposal);

            UnitOfWork.SaveChanges();

            return(__newProposal.Entity);
        }
Exemple #19
0
        // First message that's received from controller.
        private bool HandleIntroductionMessage(object body)
        {
            Newtonsoft.Json.Linq.JObject jObjectBody = (Newtonsoft.Json.Linq.JObject)body;
            var message = jObjectBody.ToObject <Dictionary <string, object> >();

            double controllerHeartbeat = Convert.ToDouble(message["heartbeat_period"]);

            updateHeartbeatPeriod(controllerHeartbeat);

            return(true);
        }
Exemple #20
0
        public string MultiParam(dynamic param)
        {
            //方式一.通过key动态的获取对应数据,并根据需要进行转换
            var teacher = param.Teacher.ToString();
            var course  = Newtonsoft.Json.JsonConvert.DeserializeObject <Course>(param.Course.ToString());

            //方式二.对应动态类型中包括的子对象也可以通过jObject类型转换
            Newtonsoft.Json.Linq.JObject jObject = param.Course;
            var courseModel = jObject.ToObject <Course>();

            return($"Teacher={teacher} CourseName={course.CourseName} CoursePrice={course.Price} CourseId={course.Id}");
        }
        public virtual void ExecuteVoidAJAX(MethodDTO pMethode)
        {
            //gb - Récupération de l'objet au format string
            string lValue = ((string[])(pMethode.Parametrage))[0];

            //gb - Convertion de l'objet au format JObject
            Newtonsoft.Json.Linq.JObject lData = JsonConvert.DeserializeObject <dynamic>(lValue);
            //gb - Convertion de l'objet au format choisi
            pMethode.Parametrage = lData.ToObject(Type.GetType(String.Format(FormatStringDTO, pMethode.DTOStringType)));
            //gb - Appel la méthode ExecuteVoid du métier
            ExecuteVoidInternal(pMethode);
        }
Exemple #22
0
        public static List <string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
        {
            Newtonsoft.Json.Linq.JObject attributesAsJObject = dynamicToGetPropertiesFor;
            Dictionary <string, object>  values = attributesAsJObject.ToObject <Dictionary <string, object> >();
            List <string> toReturn = new List <string>();

            foreach (string key in values.Keys)
            {
                toReturn.Add(key);
            }
            return(toReturn);
        }
        public string MultiParam(dynamic param)
        {
            //方式1:通过key动态的获取对应的数据,并根据需要转换
            var teacher = param.Teacher.ToString();
            var course  = Newtonsoft.Json.JsonConvert.DeserializeObject <Course>(param.Course.ToString());

            //方式2:对应动态类型中包括的子对象也可以通过jObject类型转换(下面的效果和上面是一样)
            Newtonsoft.Json.Linq.JObject jCourse = param.Course;
            var courseModel = jCourse.ToObject <Course>();//讲jsonObject转换成具体的实体对象

            return($"Teacher={teacher}  Course>Id={course.Id}  CourseName={course.Name}");
        }
 // [Authorize]
 public async Task <object> AddFullMovieDetails([FromBody] Newtonsoft.Json.Linq.JObject fullMovie)
 {
     try
     {
         var movieDetails = fullMovie.ToObject <FullMovie>();
         return(await _movieRepository.AddToDBFullMovieDeails(movieDetails));
     }
     catch (Exception ex)
     {
         _logger.LogError("create new movie failed");
         throw ex;
     }
 }
Exemple #25
0
        public static IEmu Load(string cfgFile = "EmuCfg.json")
        {
            var cfgStr = File.ReadAllText(cfgFile);

            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(cfgStr);
            string className = (string)obj["ClassName"];
            IEmu   result;

            switch (className)
            {
            case "TcpEmu":
                result = obj.ToObject <TcpEmu>();
                return(result);

            case "SerialEmu":
                result = obj.ToObject <SerialEmu>();
                return(result);

            default:
                throw new NotImplementedException(className);
            }
        }
        public ActionResult Details(string Id)
        {
            IncidentViewModel incidentView = null;

            using (IncidentAPIClient client = IncidentApiHelper.GetIncidentAPIClient())
            {
                var result = client.IncidentOperations.GetById(Id);
                Newtonsoft.Json.Linq.JObject jobj = (Newtonsoft.Json.Linq.JObject)result;
                Incident incident = jobj.ToObject <Incident>();
                incidentView = IncidentMapper.MapIncidentModelToView(incident);
            }

            return(View(incidentView));
        }
Exemple #27
0
        public ActionResult GetSerializedPerson()
        {
            Person p = new Person();

            if (Session["person"] != null)
            {
                Newtonsoft.Json.Linq.JObject jsonObj = Session["person"] as Newtonsoft.Json.Linq.JObject;
                if (jsonObj != null)
                {
                    p = jsonObj.ToObject <Person>();
                }
            }
            return(View(p));
        }
Exemple #28
0
        /// <summary>
        /// Deserializes a request, it will convert a previous schema version to the current RequestDTO.
        /// </summary>
        /// <param name="json">The json to deserialize to a <see cref="DTO.QueryComposer.QueryComposerRequestDTO"/>.</param>
        /// <returns></returns>
        public static DTO.QueryComposer.QueryComposerRequestDTO DeserializeRequest(string json)
        {
            Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json.Trim());

            var serializationSettings = new Newtonsoft.Json.JsonSerializerSettings();

            serializationSettings.Converters.Add(new DTO.QueryComposer.QueryComposerResponsePropertyDefinitionConverter());
            serializationSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.IgnoreAndPopulate;
            Newtonsoft.Json.JsonSerializer serializer = Newtonsoft.Json.JsonSerializer.Create(serializationSettings);

            if (obj.ContainsKey("SchemaVersion"))
            {
                return(obj.ToObject <DTO.QueryComposer.QueryComposerRequestDTO>(serializer));
            }

            var query = obj.ToObject <DTO.QueryComposer.QueryComposerQueryDTO>(serializer);

            var requestDTO = new DTO.QueryComposer.QueryComposerRequestDTO
            {
                Header = new DTO.QueryComposer.QueryComposerRequestHeaderDTO
                {
                    ID          = query.Header.ID,
                    Name        = query.Header.Name,
                    Description = query.Header.Description,
                    DueDate     = query.Header.DueDate,
                    Priority    = query.Header.Priority,
                    SubmittedOn = query.Header.SubmittedOn,
                    ViewUrl     = query.Header.ViewUrl
                },
                Queries = new[] {
                    query
                }
            };

            return(requestDTO);
        }
        public JsonResult ExemploNewtonSoft([FromBody] Newtonsoft.Json.Linq.JObject dados)
        {
            //Usa classes e deserializa para objeto
            Models.FamiliaDonald familia = dados.ToObject <Models.FamiliaDonald>();

            //Item-item
            string tio   = dados["tio"].ToString();
            int    idade = dados.Value <int>("idade");

            var sobrinhos = dados["sobrinhos"].ToArray();

            foreach (var item in sobrinhos)
            {
                string nome = item["nome"].ToString();
            }

            //Deserializando para objetos anônimos.
            dynamic objDyn =
                Newtonsoft.Json.JsonConvert.DeserializeObject(dados.ToString());

            tio   = objDyn.tio;
            idade = objDyn.idade;

            Newtonsoft.Json.Linq.JArray sobrinhos2 =
                objDyn.sobrinhos;

            //Exemplo de objeto anônimo

            var obj = new
            {
                nome      = "Andre",
                idade     = 38,
                sobrinhos = new object[] {
                    new {
                        nome = "111"
                    },
                    new {
                        nome = "222"
                    }
                }
            };



            return(Json(new
            {
            }));
        }
Exemple #30
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            //Load Settings from JSon file "Settings.json"
            Newtonsoft.Json.Linq.JObject jo = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(File.ReadAllText("Settings.json"));
            settings = jo.ToObject <GameSettings>();

            //Set window properties
            this.Width  = settings.WindowWidth;
            this.Height = settings.WindowHeight;
            this.Title  = settings.Title;

            //Load Textures
            GraphicsHandler.Begin(settings.TexturePath);
        }