如何将指定JSON响应反序列化为无预定义类的C#自定义对象
Alright, let's figure this out for you. You've got a JSON response that doesn't fit with the pre-defined class workflows your documentation covers—here are two practical approaches to handle this, depending on whether you want quick dynamic access or strong typing for long-term use.
First, let's restate your JSON response for clarity:
[ { "Issue": { "ID": 80, "Name": "Cold", "Accuracy": 90, "Icd": "J00", "IcdName": "Acute nasopharyngitis [common cold]", "ProfName": "Common cold", "Ranking": 1 }, "Specialisation": [ { "ID": 15, "Name": "General practice", "SpecialistID": 0 } ] } ]
1. Dynamic Handling (No Pre-Defined Classes Needed)
If you just need to access the data quickly without setting up classes, most languages support parsing JSON into dynamic objects or dictionaries.
Example in Python
Use the built-in json module to parse directly into a list of dictionaries:
import json # Your raw JSON response json_str = '''[ { "Issue": { "ID": 80, "Name": "Cold", "Accuracy": 90, "Icd": "J00", "IcdName": "Acute nasopharyngitis [common cold]", "ProfName": "Common cold", "Ranking": 1 }, "Specialisation": [ { "ID": 15, "Name": "General practice", "SpecialistID": 0 } ] } ]''' # Parse the JSON results = json.loads(json_str) # Access the first result's data first_result = results[0] # Get Issue details issue_id = first_result["Issue"]["ID"] common_name = first_result["Issue"]["ProfName"] accuracy = first_result["Issue"]["Accuracy"] # Get Specialisation details primary_specialty = first_result["Specialisation"][0]["Name"]
Example in C#
Use dynamic with System.Text.Json to avoid class definitions:
using System; using System.Text.Json; var jsonStr = @"[ { ""Issue"": { ""ID"": 80, ""Name"": ""Cold"", ""Accuracy"": 90, ""Icd"": ""J00"", ""IcdName"": ""Acute nasopharyngitis [common cold]"", ""ProfName"": ""Common cold"", ""Ranking"": 1 }, ""Specialisation"": [ { ""ID"": 15, ""Name"": ""General practice"", ""SpecialistID"": 0 } ] } ]"; // Deserialize into a dynamic array var results = JsonSerializer.Deserialize<dynamic[]>(jsonStr); var firstResult = results[0]; // Access fields directly int issueId = firstResult.Issue.ID; string specialtyName = firstResult.Specialisation[0].Name;
2. Create Custom Classes for Strong Typing
If you want the safety and maintainability of strong types, you can define classes that exactly match the JSON structure. This works even if your docs don't cover custom classes—you just mirror the JSON's nested structure.
Example in C#
Define classes that map to each nested object in the JSON:
public class MedicalResult { public Issue Issue { get; set; } public List<Specialisation> Specialisation { get; set; } } public class Issue { public int ID { get; set; } public string Name { get; set; } public int Accuracy { get; set; } public string Icd { get; set; } public string IcdName { get; set; } public string ProfName { get; set; } public int Ranking { get; set; } } public class Specialisation { public int ID { get; set; } public string Name { get; set; } public int SpecialistID { get; set; } } // Then deserialize into your strong type: var results = JsonSerializer.Deserialize<List<MedicalResult>>(jsonStr); var firstResult = results[0]; // Now you get intellisense and type safety! var icdCode = firstResult.Issue.Icd;
Example in Python
Use dataclasses to create type-safe classes:
from dataclasses import dataclass from typing import List import json @dataclass class Issue: ID: int Name: str Accuracy: int Icd: str IcdName: str ProfName: str Ranking: int @dataclass class Specialisation: ID: int Name: str SpecialistID: int @dataclass class MedicalResult: Issue: Issue Specialisation: List[Specialisation] # Parse JSON and convert to dataclasses json_str = '''[ { "Issue": { "ID": 80, "Name": "Cold", "Accuracy": 90, "Icd": "J00", "IcdName": "Acute nasopharyngitis [common cold]", "ProfName": "Common cold", "Ranking": 1 }, "Specialisation": [ { "ID": 15, "Name": "General practice", "SpecialistID": 0 } ] } ]''' raw_data = json.loads(json_str) first_result = MedicalResult( Issue=Issue(**raw_data[0]["Issue"]), Specialisation=[Specialisation(**spec) for spec in raw_data[0]["Specialisation"]] ) # Access with type safety print(f"Recommended specialty: {first_result.Specialisation[0].Name}")
Either approach should solve your problem—dynamic handling is great for quick scripts or one-off use, while custom classes are better for larger projects where you want to avoid typos and get IDE support.
内容的提问来源于stack exchange,提问作者Stevan Marjanović

