Json один дротик / флаттер для ресурсов FHIR - PullRequest
1 голос
/ 03 февраля 2020

Я пытаюсь создать классы Dart для ресурсов FHIR, определенных в Json. Полная Json схема для FHIR здесь , если кто-то хочет посмотреть. Моя проблема связана с декларацией oneOf. В частности, у меня есть класс, подобный следующему (я не включаю здесь полное определение класса, хотя могу, если кто-то посчитает, что это будет полезно):

class Bundle_Entry {
  Resource resource;

Bundle_Entry(this.resource});

  factory Bundle_Entry.fromJson(Map<String, dynamic> json) => _$Bundle_EntryFromJson(json);
  Map<String, dynamic> toJson() => _$Bundle_EntryToJson(this);
} 

Моя проблема в том, что ResourceList определяется как oneOf из ряда других классов.

"ResourceList": {
  "oneOf": [
    { "$ref": "#/definitions/Account" },
    { "$ref": "#/definitions/ActivityDefinition" },
    ...
  ]
}

Я попытался объявить переменную 'resource' как типы 'var', 'dynamici c' и 'ResourceList' и создал класс ResourceList, который просто содержит ресурс.

Каждый ресурс имеет поле с именем 'resourceType', поэтому я также попытался создать функцию ResourceList, которая возвращает разные типы на основе аргумента 'resourceType', который также не работает.

Если я сделаю http-запрос, фактический ответ, который я пытаюсь проанализировать, будет выглядеть следующим образом:

{
  "resourceType": "Bundle",
  "type": "searchset",
  "entry": [
      {
          "resource": {
              "name": "Jaba the Hutt"
              "birthDate": "1980-07-27",
              "id": "b26646dd-c549-4981-834e-bb4145d104b8",
              "resourceType": "Patient"
           }
      }
    ]
}

Буду признателен за любые предложения.

Обновление моего вопроса. Интересно, что первый ответ похож на то, что я придумал в настоящее время.

class Bundle_Entry {
  dynamic resource;
  Bundle_Entry({this.resource});

  Bundle_Entry.fromJson(Map<String, dynamic> json) =>
      Bundle_Entry(
        resource: json['resource'] == null
        ? null
        : ResourceTypes(
            json['resource']['resourceType'], json['resource'] as Map<String, dynamic>)
);}

  Map<String, dynamic> toJson() => _$Bundle_EntryToJson(this);
}

dynamic ResourceTypes(String type, Map<String, dynamic> json) {
  if (type == 'Element') return (new Element.fromJson(json));
  if (type == 'Extension') return (new Extension.fromJson(json));
  if (type == 'Patient') return (new Narrative.fromJson(json));

Моя проблема в том, что тогда мне приходится жестко кодировать каждый ResourceType, и казалось, что должно быть проще способ.

1 Ответ

0 голосов
/ 24 февраля 2020

Я пытался построить подобную вещь. Я подошел к нему с помощью наследования и создал функцию для возврата ресурса на основе поля ResourceType.

Resource getResource(json) {
  if(json == null) return null;
  if(json["resourceType"] == "Patient") return Patient.fromJson(json);
  if(json["resourceType"]=="Procedure") return Procedure.fromJson(json);
  if(json["resourceType"]=="Encounter") return Encounter.fromJson(json);
  if(json["resourceType"]=="Appointment") return Appointment.fromJson(json);
  if(json["resourceType"]=="Slot") return Slot.fromJson(json);
  if(json["resourceType"]=="Slot") return Slot.fromJson(json);
  if(json["resourceType"]=="Observation") return Observation.fromJson(json);
  if(json["resourceType"]=="Condition") return Condition.fromJson(json);
  if(json["resourceType"]=="DiagnosticReport") return DiagnosticReport.fromJson(json);
  if(json["resourceType"]=="MedicationRequest") return MedicationRequest.fromJson(json);
  if(json["resourceType"]=="CarePlan") return CarePlan.fromJson(json);
  if(json["resourceType"]=="Practitioner") return Practitioner.fromJson(json);
  if(json["resourceType"]=="AllergyIntolerance") return AllergyIntolerance.fromJson(json);

  return Resource.fromJson(json);
}

Где пациент, процедура и т. Д. c. являются подклассами ресурса:

class Entry {
  String fullUrl;
  Resource resource;

  factory Entry.fromJson(Map<String, dynamic> json) => Entry(
        fullUrl: json["fullUrl"] == null ? null : json["fullUrl"],

        //This line is the magic
        resource: getResource(json["resource"]),
        search: json["search"] == null ? null : Search.fromJson(json["search"]),
        response: json["response"] == null
            ? null
            : Response.fromJson(json["response"]),
      );

...