jdog
jdog

Reputation: 10759

Access nested objects in json using json_serializable in Dart

Trying to convert my json to objects in Dart/Flutter using the json_serializable. I cannot seem to find a way to access a nested ID (data is coming from MongoDB thus the $ in the json).

Here is the json:

{
    "_id": {
        "$oid": "5c00b227"  <-- this is what I am trying to access 
    },
    "base": 1,
    "tax": 1,
    "minimum": 5,
    "type": "blah"
}

Result:

class Thing {
  final int id;
  final String base;
  final String tax;
  final String type;
  final int minimum;
}

Upvotes: 5

Views: 2629

Answers (2)

awaik
awaik

Reputation: 12335

It is not possible with json_serializable package itself. You have to create separate objects for getting this nested data. Look the discussion here https://github.com/google/json_serializable.dart/issues/490

But, there is possible way to get nested fields with added converter (solution was found here https://github.com/google/json_serializable.dart/blob/master/example/lib/nested_values_example.dart)

import 'package:json_annotation/json_annotation.dart';

part 'nested_values_example.g.dart';

/// An example work-around for
/// https://github.com/google/json_serializable.dart/issues/490
@JsonSerializable()
class NestedValueExample {
  NestedValueExample(this.nestedValues);

  factory NestedValueExample.fromJson(Map<String, dynamic> json) =>
      _$NestedValueExampleFromJson(json);

  @_NestedListConverter()
  @JsonKey(name: 'root_items')
  final List<String> nestedValues;

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

class _NestedListConverter
    extends JsonConverter<List<String>, Map<String, dynamic>> {
  const _NestedListConverter();

  @override
  List<String> fromJson(Map<String, dynamic> json) => [
        for (var e in json['items'] as List)
          (e as Map<String, dynamic>)['name'] as String
      ];

  @override
  Map<String, dynamic> toJson(List<String> object) => {
        'items': [
          for (var item in object) {'name': item}
        ]
      };
}

Upvotes: 4

Dhanaji Yadav
Dhanaji Yadav

Reputation: 1422

try this,

class Thing {
   int id;
   String base;
   String tax;
   String type;
   int minimum;

   Thing({
    this.id,
    this.base,
    this.tax,
    this.type,
    this.minimum,
  });

   factory Thing.fromJson(Map<String, dynamic> json) {
     return Thing(
       id: json['_id']["oid"],
       base: json['base'].toString(),
       tax: json['tax'].toString(),
       type: json['type'].toString(),
       minimum: json['minimum'],
     );
   }
}

Upvotes: 0

Related Questions