Hello,
I want to read json file data with specific json object array one by one using Foreach loop in Asp.net Core.
I Have MasterData.json file
- {
- "M203StructureKind": [
- {
- "Code": "1",
- "Description": "BRIDGE"
- },
- {
- "Code": "2",
- "Description": "CULVERT"
- },
- {
- "Code": "3",
- "Description": "TUNNEL"
- },
- {
- "Code": "4",
- "Description": "TRAIL BRIDGE"
- },
- {
- "Code": "5",
- "Description": "OTHER"
- }
- ]
- }
So, Now i want to read one by one and insert into database. Below is my code
- [HttpPut("copyMasterData/{id}")]
- public async Task<IActionResult> CopyMasterData(int id, bool isCopiedData)
- {
- try
- {
- var folderDetails = Path.Combine(Directory.GetCurrentDirectory(), $"wwwroot\\{"MasterData\\masterdata.json"}");
- var JSON = System.IO.File.ReadAllText(folderDetails);
- dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(JSON);
- var response = 0;
- foreach (var item in jsonObj["M203structureKind"])
- {
- var m203StructureKind = new M203structureKind
- {
- Code = item ["Code"].ToString(),
- Description = item ["Description"].ToString(),
- AgencyId = id,
- IsActive = true,
- IsDeleted = false,
- AddedBy = User.GetUserId(),
- ModifiedBy = User.GetUserId()
- AddedOn = DateTime.Now,
- ModifiedOn = DateTime.Now
- };
- response = await _m203structkindService.AddAsync(m203StructureKind);
- }
- n response > 0 ? Ok(new { message = "Agency details added successfully." }) : StatusCode(500, "An error occured while adding agency details. Please try again...");
- }
- catch (Exception ex)
- {
- return StatusCode(500, ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.Add, ex.Message));
- }
- }