C#/.Net MVC项目关联JSON与SQL应使用哪种JSON Schema?
Hey there! Let's walk through this step by step since you're new to working with JSON in a C#/.NET MVC project—no stress, we'll get you on track.
First off, don't overcomplicate JSON Schema for your use case. Schema is mainly for validating that your JSON matches a specific structure, and it should align directly with the model class you've already created (since that model is tied to your SQL database).
For example, if your model is a Customer class with properties like Id, Name, and Email, your JSON Schema should mirror that structure. You can even auto-generate the schema from your model using tools built into .NET:
- If you're using
System.Text.Json(built into .NET Core 3.0+), you can useJsonSchemaGenerator(from theSystem.Text.Json.Schemapackage) to generate a schema that matches your model. - For older MVC projects using Newtonsoft.Json (Json.NET), use
JsonSchemaGeneratorfrom theNewtonsoft.Json.Schemapackage.
The key here is: your schema should reflect your model, which in turn reflects your SQL database table. So start by making sure your model class maps correctly to your SQL table (use Entity Framework Data Annotations or Fluent API for this if you haven't already).
You have two main scenarios here, depending on whether you're reading from JSON to populate SQL, or reading from SQL to return JSON:
Scenario 1: Populate SQL from a JSON File
If you need to take data from your JSON file and save it to your SQL database, do this:
// 1. Read the JSON file content string jsonFilePath = @"C:\YourProject\Models\your-data.json"; string jsonContent = System.IO.File.ReadAllText(jsonFilePath); // 2. Deserialize JSON into your model collection (replace YourModel with your actual class) List<YourModel> dataItems = System.Text.Json.JsonSerializer.Deserialize<List<YourModel>>(jsonContent); // 3. Save to SQL using Entity Framework using (var dbContext = new YourDbContext()) { dbContext.YourModels.AddRange(dataItems); dbContext.SaveChanges(); }
Scenario 2: Return SQL Data as JSON (for GET requests)
When you need to pull data from SQL and send it as JSON to the client, use your EF context to fetch data, then let MVC handle serialization:
public class YourController : Controller { private readonly YourDbContext _dbContext; // Inject your DB context via constructor (dependency injection) public YourController(YourDbContext dbContext) { _dbContext = dbContext; } // GET: /YourController/GetAllData [HttpGet] public IActionResult GetAllData() { var data = _dbContext.YourModels.ToList(); return Json(data); // MVC automatically serializes the list to JSON } }
GET Requests with Callback Support
If you need to support JSONP (for cross-domain requests with callbacks), modify your GET action to check for a callback query parameter:
[HttpGet] public IActionResult GetDataWithCallback() { var data = _dbContext.YourModels.ToList(); string callback = Request.Query["callback"]; // If a callback is provided, return JSONP (wrapped in the callback function) if (!string.IsNullOrEmpty(callback)) { string jsonContent = System.Text.Json.JsonSerializer.Serialize(data); return Content($"{callback}({jsonContent})", "application/javascript"); } // Otherwise, return standard JSON return Json(data); }
On the front end, you'd call this like yourdomain.com/YourController/GetDataWithCallback?callback=handleResponse, and the response will be handleResponse([your-json-data]).
POST Requests to Save JSON Data
To accept JSON from a client and save it to SQL, use the [FromBody] attribute to bind the JSON to your model:
// POST: /YourController/SaveData [HttpPost] public IActionResult SaveData([FromBody] YourModel newItem) { if (ModelState.IsValid) { _dbContext.YourModels.Add(newItem); _dbContext.SaveChanges(); // Return a success response that the front end can use in its callback return Json(new { Success = true, Message = "Data saved!", ItemId = newItem.Id }); } // Return validation errors if the JSON doesn't match your model schema return BadRequest(ModelState); }
Front-end code can send a POST request with JSON body, then use a success callback to handle the response.
- Stick with
System.Text.Jsonif you're on .NET Core 3.0+ (it's built-in and performant). For older MVC 5 projects, use Newtonsoft.Json. - Double-check that your model class properties match your SQL table columns (use
[Key],[Column]attributes if needed for EF mapping). - Test your endpoints with tools like Postman or Swagger to verify JSON serialization/deserialization works as expected.
内容的提问来源于stack exchange,提问作者Itzik

