hiranthaR / Json-to-Dart-Model

Json to Dart Model extension can convert JSON objects into Dart data classes. It supports pure Dart class conversion, Flutter-recommended JSON serialization using annotations, Freezed support, Effective Dart:Style, and many more features. Currently, it has more than 135,000 installs.
https://marketplace.visualstudio.com/items?itemName=hirantha.json-to-dart
MIT License
93 stars 17 forks source link

Support Map type #97

Open princ3od opened 2 years ago

princ3od commented 2 years ago

It would be great if Json-to-Dart-Model supported Map data type as it already supported List. Currrently, if the key is something like "key.Map":{}, it creates a whole new class called Map. I think it should use the existed Map class of Dart. Thank you.

iamarnas commented 2 years ago

@princ3od Hi 👋 Thanks for suggestion. I wonder you mean MapView?

Example:

class Person extends MapView<String, String> { 
   final String firstName; 
   final String lastName; 
   Person(this.firstName, this.lastName) 
       : super( 
           { 
             'first_name': firstName, 
             'last_name': lastName, 
           }, 
         ); 
 }

source

princ3od commented 2 years ago

Thanks for replying @iamarnas. But I mean I have a json as show below

{
  "__className": "Topic",
  "id": "sport",
  "is_stored": true,
  "name": "Sport",
  "articles.Map": {}
}

My expected output will be

import 'package:freezed_annotation/freezed_annotation.dart';

part 'topic.freezed.dart';
part 'topic.g.dart';

@freezed
class Topic with _$Topic {
  factory Topic({
    String? id,
    String? name,
    @JsonKey(name: 'is_stored') bool? isStored,
    Map articles,
  }) = _Topic;

  factory Topic.fromJson(Map<String, dynamic> json) => _$TopicFromJson(json);
}

And the Map type should be Map class of Dart. Currently, it will create a new class called Map.

iamarnas commented 2 years ago

@princ3od In this way "articles.Map": { ... } you force rename object type with this generator, but it just not work with primitive values. Have you tried it? I don't remember if Map is allowed. By using Freezed it would be possible to allow it.

princ3od commented 2 years ago

I tried it and it did not work. So how can I generate a class with a Map type field? I see List type field is already supported.

iamarnas commented 2 years ago

I tried it and it did not work. So how can I generate a class with a Map type field? I see List type field is already supported.

If it doesn't work then it's not allowed. List supported becouse it generates with this generator but Map not. Need to implement.

@princ3od

clivi-kj commented 2 years ago

also looking for this. would be helpful for Firestore conversions.