DICOM JSON을 Dataset 또는 DicomFile로 돌려보내는 방법
이 튜토리얼은 DICOM JSON을 C#를 사용하여 Dataset 또는 DicomFile 개체로 돌아가게하는 방법을 보여줍니다.이 능력은 데이터베이스에 저장되거나 웹 APIs에서 수신 된 jSON에서 DIKOM 데이터를 재구성해야 할 때 필수적입니다.
JSON Deserialization의 혜택
- 데이터 재구성* :- 데이터베이스에 저장된 JSON에서 DICOM 파일을 복원합니다.
- API 통합* :- 웹 서비스에서 JSON로 수신된 DICOM 데이터를 처리합니다.
** 라운드 트리프 처리** :- JSON으로 시리얼링, 수정, 다음 DICOM으로 다시 deserialize.
원제 : Environment Preparation
- Visual Studio 또는 모든 호환되는 .NET IDE를 설정합니다.
- 새로운 .NET 8 콘솔 애플리케이션 프로젝트를 만드십시오.
- NuGet 패키지 관리자에서 Aspose.Medical을 설치합니다.
Deserialization 옵션 이해
DicomJsonSerializer는 다양한 퇴화 방법을 제공합니다 :
| 방법 | Input | 출력 | 사용 사례 |
|---|---|---|---|
Deserialize | JSON 스트리트 | Dataset? | JSON의 단일 데이터 세트 |
DeserializeFile | JSON 스트리트 | DicomFile? | 메타 정보로 완성된 DICOM 파일 |
DeserializeList | JSON 아레이 스트리트 | Dataset[]? | JSON Array의 다중 데이터 세트 |
DICOM JSON을 탐색하기 위한 단계별 가이드
단계 1 : Aspose.Medical 설치
NuGet을 사용하여 프로젝트에 Aspose.Medical 도서관을 추가합니다.
Install-Package Aspose.Medical단계 2 : 필요한 이름 공간을 포함
코드에 필요한 이름 공간에 참조를 추가합니다.
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;3단계 : JSON 콘텐츠 읽기
파일 또는 변수에서 JSON 콘텐츠를 읽으십시오.
string jsonText = File.ReadAllText("patient_scan.json");단계 4 : 데이터 세트를 탐색
사용하기 Deserialize 데이터 세트 개체를 재구성합니다.
Dataset? dataset = DicomJsonSerializer.Deserialize(jsonText);5단계: 데이터 세트 작업
재구성된 데이터 세트에 액세스하고 조작하십시오.
if (dataset != null)
{
Console.WriteLine("Dataset successfully reconstructed from JSON.");
// Work with the dataset...
}단계 6 : DICOM으로 다시 저장 (선택)
새로운 DicomFile를 만들고 디스크에 저장합니다.
if (dataset != null)
{
DicomFile newDcm = new DicomFile(dataset);
newDcm.Save("reconstructed.dcm");
}완전한 코드 예: 단일 데이터 세트를 탐색
다음은 단일 데이터 세트를 비현하는 방법을 보여주는 완전한 예입니다 :
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Read JSON from file
string jsonText = File.ReadAllText("patient_scan.json");
// Deserialize to Dataset
Dataset? dataset = DicomJsonSerializer.Deserialize(jsonText);
if (dataset != null)
{
Console.WriteLine("Dataset successfully deserialized!");
// Create a new DicomFile with the dataset
DicomFile newDcm = new DicomFile(dataset);
// Save to DICOM format
newDcm.Save("reconstructed_scan.dcm");
Console.WriteLine("Saved to reconstructed_scan.dcm");
}
else
{
Console.WriteLine("Failed to deserialize JSON.");
}완전한 디컴필을 탐색
JSON 파일 메타 정보를 포함하는 경우, 사용 DeserializeFile:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Read JSON that includes file meta information
string jsonFileText = File.ReadAllText("complete_dicom.json");
// Deserialize to complete DicomFile
DicomFile? dicomFile = DicomJsonSerializer.DeserializeFile(jsonFileText);
if (dicomFile != null)
{
Console.WriteLine("DicomFile successfully deserialized!");
dicomFile.Save("reconstructed_complete.dcm");
}JSON Array를 다중 데이터 세트로 탐색
JSON과 함께 작업 할 때 여러 데이터 세트를 포함하는 레이어 :
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Read JSON array
string jsonArrayText = File.ReadAllText("multiple_studies.json");
// Deserialize to Dataset array
Dataset[]? datasets = DicomJsonSerializer.DeserializeList(jsonArrayText);
if (datasets != null)
{
Console.WriteLine($"Deserialized {datasets.Length} datasets.");
// Save each dataset as a separate DICOM file
for (int i = 0; i < datasets.Length; i++)
{
DicomFile dcm = new DicomFile(datasets[i]);
dcm.Save($"study_{i:D3}.dcm");
}
Console.WriteLine("All datasets saved successfully!");
}라운드 트리프 예제 : 시리화, 수정, 퇴화
일반적인 사용 사례는 JSON을 통해 DICOM 데이터를 수정하는 것입니다 :
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
using System.Text.Json;
// Load original DICOM file
DicomFile original = DicomFile.Open("original.dcm");
// Serialize to JSON
string json = DicomJsonSerializer.Serialize(original, writeIndented: true);
// Parse JSON for modification (using System.Text.Json)
using JsonDocument doc = JsonDocument.Parse(json);
// ... modify JSON as needed ...
// Deserialize back to Dataset
Dataset? modifiedDataset = DicomJsonSerializer.Deserialize(json);
if (modifiedDataset != null)
{
DicomFile modifiedDcm = new DicomFile(modifiedDataset);
modifiedDcm.Save("modified.dcm");
}데이터베이스 스토리지 작업
Deserialize DICOM JSON 데이터베이스에서 얻은:
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Simulating retrieval from database
string jsonFromDatabase = GetDicomJsonFromDatabase("patient_123");
Dataset? dataset = DicomJsonSerializer.Deserialize(jsonFromDatabase);
if (dataset != null)
{
// Process the reconstructed dataset
DicomFile dcm = new DicomFile(dataset);
dcm.Save("from_database.dcm");
Console.WriteLine("DICOM file reconstructed from database JSON.");
}
// Simulated database retrieval method
string GetDicomJsonFromDatabase(string patientId)
{
// In real implementation, this would query your database
return File.ReadAllText($"database_cache/{patientId}.json");
}웹 애플리케이션을 위한 Async Deserialization
ASP.NET 코어 응용 프로그램에서는 async 방법을 사용합니다.
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
// Async deserialization from stream
public async Task<Dataset?> DeserializeFromStreamAsync(Stream jsonStream)
{
Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(jsonStream);
return dataset;
}
// Usage in ASP.NET Core controller
[HttpPost("import")]
public async Task<IActionResult> ImportDicomJson()
{
Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(Request.Body);
if (dataset != null)
{
// Process the dataset
return Ok("DICOM data imported successfully");
}
return BadRequest("Invalid DICOM JSON");
}Troubleshooting
잘못된 JSON 처리
항상 try-catch 블록에 deserialization을 포장하십시오 :
try
{
Dataset? dataset = DicomJsonSerializer.Deserialize(jsonText);
if (dataset == null)
{
Console.WriteLine("Deserialization returned null - check JSON format.");
}
}
catch (JsonException ex)
{
Console.WriteLine($"JSON parsing error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Deserialization error: {ex.Message}");
}흔들린 JSON
큰 JSON 파일의 경우, 완전한 콘텐츠가 읽을 수 있는지 확인하십시오 :
// Use ReadAllText for complete file content
string completeJson = File.ReadAllText("large_dicom.json");
// Verify JSON is complete (basic check)
if (!completeJson.TrimEnd().EndsWith("}") && !completeJson.TrimEnd().EndsWith("]"))
{
Console.WriteLine("Warning: JSON may be truncated.");
}버전 호환성
JSON이 시리얼리저의 호환되는 버전으로 생성되었는지 확인합니다. 잘못된 버전에 대한 오류가 제거 실패를 일으킬 수 있습니다.
추가 정보
- Deserialized 데이터 세트는 원래 JSON에 삽입된 경우를 제외하고는 픽셀 데이터를 포함하지 않습니다.
- 생산 사용을 위해 JSON 입력의 적절한 인증을 제거하기 전에 실행하십시오.
- 자주 접근하는 데이터에 대한 데세리화 된 데이터 세트의 캐싱을 고려하십시오.
결론
이 튜토리얼은 Aspose.Medical을 사용하여 C#에서 Dataset 또는 DicomFile 개체로 DICOM JSON을 다시 탐색하는 방법을 보여주었습니다.이 능력은 Ronde-trip DIKOM 데이터 처리를 가능하게하고 Json 기반 스토리지 및 API 시스템과 무선 통합을 허용합니다.