How to Deserialize DICOM JSON Back to Dataset or DicomFile

How to Deserialize DICOM JSON Back to Dataset or DicomFile

This tutorial demonstrates how to deserialize DICOM JSON back to Dataset or DicomFile objects using C#. This capability is essential when you need to reconstruct DICOM data from JSON stored in databases or received from web APIs.

Benefits of JSON Deserialization

  1. Data Reconstruction:
    • Rebuild DICOM files from JSON stored in databases.
  2. API Integration:
    • Process DICOM data received as JSON from web services.
  3. Round-Trip Processing:
    • Serialize to JSON, modify, then deserialize back to DICOM.

Prerequisites: Preparing the Environment

  1. Set up Visual Studio or any compatible .NET IDE.
  2. Create a new .NET 8 console application project.
  3. Install Aspose.Medical from the NuGet Package Manager.

Understanding Deserialization Options

The DicomJsonSerializer provides different deserialization methods:

MethodInputOutputUse Case
DeserializeJSON stringDataset?Single dataset from JSON
DeserializeFileJSON stringDicomFile?Complete DICOM file with meta info
DeserializeListJSON array stringDataset[]?Multiple datasets from JSON array

Step-by-Step Guide to Deserialize DICOM JSON

Step 1: Install Aspose.Medical

Add the Aspose.Medical library to your project using NuGet.

Install-Package Aspose.Medical

Step 2: Include Necessary Namespaces

Add references to the required namespaces in your code.

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;

Step 3: Read JSON Content

Read the JSON content from a file or variable.

string jsonText = File.ReadAllText("patient_scan.json");

Step 4: Deserialize to Dataset

Use Deserialize to reconstruct a Dataset object.

Dataset? dataset = DicomJsonSerializer.Deserialize(jsonText);

Step 5: Work with the Dataset

Access and manipulate the reconstructed dataset.

if (dataset != null)
{
    Console.WriteLine("Dataset successfully reconstructed from JSON.");
    // Work with the dataset...
}

Step 6: Save Back to DICOM (Optional)

Create a new DicomFile and save to disk.

if (dataset != null)
{
    DicomFile newDcm = new DicomFile(dataset);
    newDcm.Save("reconstructed.dcm");
}

Complete Code Example: Deserialize Single Dataset

Here is a complete example demonstrating how to deserialize a single dataset:

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.");
}

Deserialize Complete DicomFile

When your JSON includes file meta information, use 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");
}

Deserialize JSON Array to Multiple Datasets

When working with JSON arrays containing multiple datasets:

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!");
}

Round-Trip Example: Serialize, Modify, Deserialize

A common use case is modifying DICOM data through JSON:

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");
}

Working with Database Storage

Deserialize DICOM JSON retrieved from a database:

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 for Web Applications

For ASP.NET Core applications, use async methods:

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

Handling Malformed JSON

Always wrap deserialization in try-catch blocks:

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}");
}

Handling Truncated JSON

For large JSON files, ensure complete content is read:

// 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.");
}

Version Compatibility

Ensure the JSON was generated with a compatible version of the serializer. Mismatched versions may cause deserialization failures.

Additional Information

  • Deserialized datasets do not include pixel data unless it was embedded in the original JSON.
  • For production use, implement proper validation of JSON input before deserialization.
  • Consider caching deserialized datasets for frequently accessed data.

Conclusion

This tutorial has demonstrated how to deserialize DICOM JSON back to Dataset or DicomFile objects in C# using Aspose.Medical. This capability enables round-trip DICOM data processing and seamless integration with JSON-based storage and API systems.

 English