Adhikar Patil

Adhikar Patil

  • NA
  • 481
  • 122.5k

How to Read Json File Data in Asp.Net Core of Specific Json

Oct 11 2019 11:36 AM
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
  1. {  
  2. "M203StructureKind": [  
  3. {  
  4. "Code""1",  
  5. "Description""BRIDGE"  
  6. },  
  7. {  
  8. "Code""2",  
  9. "Description""CULVERT"  
  10. },  
  11. {  
  12. "Code""3",  
  13. "Description""TUNNEL"  
  14. },  
  15. {  
  16. "Code""4",  
  17. "Description""TRAIL BRIDGE"  
  18. },  
  19. {  
  20. "Code""5",  
  21. "Description""OTHER"  
  22. }  
  23. ]  
  24. }  
So, Now i want to read one by one and insert into database. Below is my code
  1. [HttpPut("copyMasterData/{id}")]  
  2. public async Task<IActionResult> CopyMasterData(int id, bool isCopiedData)  
  3. {  
  4. try  
  5. {  
  6. var folderDetails = Path.Combine(Directory.GetCurrentDirectory(), $"wwwroot\\{"MasterData\\masterdata.json"}");  
  7. var JSON = System.IO.File.ReadAllText(folderDetails);  
  8. dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(JSON);  
  9. var response = 0;  
  10. foreach (var item in jsonObj["M203structureKind"])  
  11. {  
  12. var m203StructureKind = new M203structureKind  
  13. {  
  14. Code = item ["Code"].ToString(),  
  15. Description = item ["Description"].ToString(),  
  16. AgencyId = id,  
  17. IsActive = true,  
  18. IsDeleted = false,  
  19. AddedBy = User.GetUserId(),  
  20. ModifiedBy = User.GetUserId()  
  21. AddedOn = DateTime.Now,  
  22. ModifiedOn = DateTime.Now  
  23. };  
  24. response = await _m203structkindService.AddAsync(m203StructureKind);  
  25. }  
  26. n response > 0 ? Ok(new { message = "Agency details added successfully." }) : StatusCode(500, "An error occured while adding agency details. Please try again...");  
  27. }  
  28. catch (Exception ex)  
  29. {  
  30. return StatusCode(500, ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.Add, ex.Message));  
  31. }  
  32. }  

Answers (2)