根据Phone字段值提取对应JSON字段的实现方法咨询
Phone Value Hey there! Let's work through this problem together. Here's a clear, step-by-step approach to extract the right JSON fields based on the Phone value in your loop:
1. Prepare Your JSON Data & Target Phone Types
First, make sure your dynamic JSON is parsed into a traversable structure. Assuming you're using Newtonsoft.Json (Json.NET) (the most common library for C# JSON handling), parse your input into a JArray (if your JSON is an array of objects).
Also, define a set of target Phone values to avoid repeating conditional checks—this makes your code cleaner and faster for lookups:
// Parse your JSON string into a JArray var jsonResult = JsonConvert.DeserializeObject<JArray>(yourRawJsonString); // Define the Phone values we care about (use HashSet for O(1) lookups) var targetPhoneTypes = new HashSet<string> { "PSTN", "UIFN", "TS", "RS", "TF" };
2. Loop Through Items & Extract Matching Fields
In your foreach loop, first safely retrieve the Phone value from each item, check if it's in our target set, then extract the field with the same name as the Phone value. Always handle nulls to avoid runtime exceptions:
foreach (var item in jsonResult) { // Safely get the Phone value (null checks to avoid crashes) if (item["Phone"]?.Value<string>() is string phoneType && targetPhoneTypes.Contains(phoneType)) { // Extract the field matching the Phone value var targetField = item[phoneType]; if (targetField != null) { // Do something with the extracted field—example: print it or store it Console.WriteLine($"Extracted {phoneType} value: {targetField.ToString()}"); // If you need a specific type, convert it: // string fieldValue = targetField.Value<string>(); // int numericValue = targetField.Value<int>(); } } }
3. Alternative: Using System.Text.Json (Built-in .NET Library)
If you prefer using the built-in System.Text.Json instead of Json.NET, the logic is nearly identical—you'll just work with JsonElement instead of JObject:
// Parse the JSON into a JsonDocument using var jsonDoc = JsonDocument.Parse(yourRawJsonString); var jsonResult = jsonDoc.RootElement.EnumerateArray(); var targetPhoneTypes = new HashSet<string> { "PSTN", "UIFN", "TS", "RS", "TF" }; foreach (var item in jsonResult) { // Safely retrieve the Phone property and its value if (item.TryGetProperty("Phone", out JsonElement phoneElement) && phoneElement.ValueKind == JsonValueKind.String && targetPhoneTypes.Contains(phoneElement.GetString())) { string phoneType = phoneElement.GetString(); // Extract the matching field if (item.TryGetProperty(phoneType, out JsonElement targetField)) { // Process the extracted field Console.WriteLine($"Extracted {phoneType} value: {targetField.ToString()}"); } } }
Key Notes to Avoid Issues
- Null Safety: Always check if
item["Phone"]or the target field exists before accessing their values—use?.(null-conditional operator) orTryGetPropertyto preventNullReferenceException. - Type Checks: Verify that the
Phonevalue is a string (since your targets are strings) before using it to avoid type mismatch errors. - Scalability: Using a
HashSetfor target phone types makes it easy to add/remove values later without rewriting conditionals.
内容的提问来源于stack exchange,提问作者DonDiego06

