Home > Mobile >  Converting complex JSON string to Map
Converting complex JSON string to Map

Time:03-10

When I say complex, means : A lot of nested objects, arrays, etc...

I am actually stuck on this simple thing:

// Get the result from endpoint, store in a complex model object
// and then write to secure storage.

ServerResponse rd = ServerResponse.fromMap(response.data);
appUser = AppUser.fromMap(rd.data); // appData is a complex object
await storage.write(key: keyData, value: userData);
String keyData = "my_data";
const storage = FlutterSecureStorage();
String? userData = appUser?.toJson(); // Convert the data to json. This will produce a JSON with escapes on the nested JSON elements.bear this in mind.

// Now that I stored my data, sucessfully, here comes the challenge: read it back

String dataStored = await storage.read(key: keyData);

// Now What ?

If I decide to go to appUser = AppUser.fromJson(dataStored), will be very complicated because for each level of my Json, too many fromJson, fromMap, toJson, toMap...It's nuts.

Hovever I've a fromMap that's actually works good since Dio always receive the data as Map<String, dynamic>. And my question is: Is there some way to convert a huge and complex JSON stringified to a full Map<String, dynamic> ? json.decode(dataStored) only can convert the properties on root - Nested properties will still continue as JSON string inside a map.

Any clue ??? thanks !

CodePudding user response:

This is the main problem since Dart is lacking data classes. Thus, you need to define fromJson/toJson methods by yourself. However, there are several useful packages that use code generation to cope with this problem:

  • json_serializable - basically a direct solution to your problem.
  • freezed - uses json_serializable under the hood, but also implement some extra useful methods, focusing on the immutability of your data classes.

Other than that, unfortunately, you would need to implement fromJson/toJson methods by yourself.

CodePudding user response:

This website might help you. Simply just paste your json in there and it will automatically generate fromJson/toJson methods for you, then you can custom it by yourself.

I've used it a lot for my company project and it's very helpful. Here's the link to website : link

CodePudding user response:

import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

const userJson = {
  'firstName': 'John',
  'lastName': 'Smith',
};

class User {
  final String firstName;
  final String lastName;

  const User({required this.firstName, required this.lastName});

  Map<String, dynamic> toJson() => {
        'firstName': firstName,
        'lastName': lastName,
      };

  factory User.fromJson(dynamic json) {
    return User(
      firstName: json['firstName'] as String? ?? '',
      lastName: json['lastName'] as String? ?? '',
    );
  }
}

void main() {
  test('from and to json methods', () async {
    final user = User.fromJson(userJson);
    final _userJson = user.toJson();

    debugPrint(userJson.toString());
    debugPrint(_userJson.toString());
    expect(const MapEquality().equals(userJson, _userJson), true);
  });
}

  •  Tags:  
  • dart
  • Related