Click here to Skip to main content
15,936,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I want to read json file data with specific json object array one by one using Foreach loop and insert into database in Asp.net Core.

I Have MasterData.json file

C++
{ 
"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

What I have tried:

C#
[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);
} 
return 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));
}
}
Posted
Updated 11-Oct-19 11:36am
v3
Comments
Richard Deeming 11-Oct-19 12:54pm    
What's the problem with the code you've posted?
adhikar patil 11-Oct-19 13:07pm    
I want to get M203StructureKind objects json array one by one to insert data into database table but gives me exception when i comes with looping. So kindly give me the solution for reading specific objects array one by one.
Richard Deeming 11-Oct-19 13:08pm    
And the exception is?

At a guess, you're getting a NullReferenceException because you've specified the wrong name for the property.

Your JSON file has: M203StructureKind
Your C# code is looking for: M203structureKind
Note the different case on the first "S".

JSON is based on Javascript, and is therefore case-sensitive. Change your code to use the correct case, and you will be able to read the items from the JSON file:
C#
foreach (var item in jsonObj["M203StructureKind"])

NB: If that's not the error you're getting, then you need to give us the full details of the exception.
 
Share this answer
 
Comments
adhikar patil 13-Oct-19 12:58pm    
Hello,
Can i insert bulk data into table from json data using entityframework core repository
I would recommend you to create a strongly-typed class for your JSON object like this:

C#
public class M203StructureKind  
{  
    public string Code { get; set; }  
    public string Description { get; set; }  
}  
  
public class RootObject  
{  
    public List<M203StructureKind> M203StructureKind { get; set; }  
}  


Then you should be able to deserialized it like in the following:

C#
var jsonStirng = "{   \"M203StructureKind\":[      {         \"Code\":\"1\",         \"Description\":\"BRIDGE\"      },      {         \"Code\":\"2\",         \"Description\":\"CULVERT\"      },      {         \"Code\":\"3\",         \"Description\":\"TUNNEL\"      },      {         \"Code\":\"4\",         \"Description\":\"TRAIL BRIDGE\"      },      {         \"Code\":\"5\",         \"Description\":\"OTHER\"      }   ]}";  
  
var root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonStirng);  
  
foreach(var item in root.M203StructureKind)  
{  
    var code = item.Code;  
    var desc = item.Description;  
  
    //Your DB INSERT logic here  
}


That way, you don't have to hard code the attribute that you want to access from the JSON object.
 
Share this answer
 
v2
Comments
adhikar patil 16-Oct-19 23:08pm    
Hello,
Can i insert bulk data into table from json data using entityframework core because i have too much table and i want to insert bulk data from json file not using foreach loop

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900