使用VB.Net读取JSON对象及Newtonsoft循环遍历JSON的技术求助
Got it, let's walk through exactly how to do this—whether your JSON is a simple array or a nested object, I'll cover the common scenarios and share actionable code snippets.
First, Basic Setup
Make sure you have the Newtonsoft.Json (Json.NET) NuGet package installed in your project. If not, you can install it via the Package Manager Console:
Install-Package Newtonsoft.Json
Scenario 1: JSON is a Simple Array of Objects
Let's say your JSON looks like this (a list of items with a Name field):
[ { "Name": "Alice", "Role": "Admin" }, { "Name": "Bob", "Role": "User" }, { "Name": "Charlie", "Role": "User" } ]
Here's how to parse it, loop through each item, and save the names to a database (using SQL Server as an example—adjust for your database type):
using Newtonsoft.Json.Linq; using System.Data.SqlClient; // Your raw JSON string string jsonData = @"[ { ""Name"": ""Alice"", ""Role"": ""Admin"" }, { ""Name"": ""Bob"", ""Role"": ""User"" }, { ""Name"": ""Charlie"", ""Role"": ""User"" } ]"; // Parse the JSON into a JArray JArray itemsArray = JArray.Parse(jsonData); // Loop through each object in the array foreach (JObject item in itemsArray) { // Safely get the Name value (avoid null reference errors with ?.) string name = item["Name"]?.ToString(); // Skip empty or null names to avoid invalid database entries if (string.IsNullOrWhiteSpace(name)) continue; // Save to database using parameterized queries (critical to prevent SQL injection!) using (SqlConnection connection = new SqlConnection("Your_Database_Connection_String")) { connection.Open(); string insertQuery = "INSERT INTO Your_Table_Name (Name) VALUES (@Name)"; using (SqlCommand command = new SqlCommand(insertQuery, connection)) { command.Parameters.AddWithValue("@Name", name); command.ExecuteNonQuery(); } } }
Scenario 2: JSON Has a Nested Array
If your JSON is wrapped in a parent object (like a Users array inside a root object):
{ "Company": "Tech Corp", "Users": [ { "Name": "Diana", "Department": "Engineering" }, { "Name": "Eve", "Department": "Marketing" } ] }
Just adjust the parsing step to target the nested array:
string nestedJson = @" { ""Company"": ""Tech Corp"", ""Users"": [ { ""Name"": ""Diana"", ""Department"": ""Engineering"" }, { ""Name"": ""Eve"", ""Department"": ""Marketing"" } ] }"; // Parse root object first JObject rootObject = JObject.Parse(nestedJson); // Get the nested Users array JArray usersArray = (JArray)rootObject["Users"]; // The rest of the loop and database code is identical to Scenario 1 foreach (JObject user in usersArray) { string name = user["Name"]?.ToString(); if (!string.IsNullOrWhiteSpace(name)) { // Save to database... } }
Bonus: Use Strongly-Typed Classes (Cleaner for Complex JSON)
If you have a consistent JSON structure, you can create a C# class to deserialize the JSON directly, which makes the code more readable:
using Newtonsoft.Json; // Define your class to match the JSON structure public class User { public string Name { get; set; } public string Department { get; set; } // Optional, if you need other fields } // Deserialize the JSON into a list of User objects List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonData); // Loop through the strongly-typed list foreach (User user in users) { if (!string.IsNullOrWhiteSpace(user.Name)) { // Save to database... } }
Key Notes to Remember
- Always use parameterized queries: Never concatenate user input (or JSON values) directly into SQL strings—this is a massive security risk (SQL injection).
- Handle null/empty values: Add checks like
string.IsNullOrWhiteSpace(name)to avoid saving invalid data to your database. - Adjust for your database: If you're using PostgreSQL, MySQL, etc., replace the
SqlConnection/SqlCommandwith the appropriate client classes (e.g.,NpgsqlConnectionfor PostgreSQL).
Hope this solves your problem! If your JSON structure is more complex than these examples, feel free to share a snippet and I can tweak the code to match.
内容的提问来源于stack exchange,提问作者Bill

