Christian
Christian

Reputation: 1058

How to convert Map<int, Map<int, Map<int, Map<int, int>>>> to json

So I have this data :

{
  2021: {
    01: {
      4: {2: 3},
      5: {2: 3},
      6: {2: 3},
      ...
    },
  },
  2022: {
    01: {
      4: {2: 3},
      5: {2: 3},
      6: {2: 3},
      ...
    },
  },
}

which is a Map<int, Map<int, Map<int, Map<int, int>>>>

The purpose of this structure is to hold information abount every day of a years calendar week like this:

    {
      year: {
        calendarweek: {
          day: {2 out of 3},
          day: {2 out of 3},
          ...
        },
      },
      year: {
        calendarweek: {
          day: {2 out of 3},
          day: {2 out of 3},
          ...
        },
      },
    }

Now I want to store this information as Json but the conversion is giving me a REALLY hard time.

So how would I de- and encode this data from/to json?

Upvotes: 1

Views: 52

Answers (1)

Indeed to encode your data to Json format, the keys should be String objects otherwise you get error messages, my example:

import 'dart:convert';

const data = {
  '2021': {
    '01': {
      '4': {'2': 3},
      '5': {'2': 3},
      '6': {'2': 3},
    },
  },
  '2022': {
    '01': {
      '4': {'2': 3},
      '5': {'2': 3},
      '6': {'2': 3},
    },
  },
};

void main(List<String> args) {
  var myData = jsonEncode(data);
  // var myData = jsonEncode({'2':3});

  print(myData.runtimeType);
  print(myData);
}

Result:

String
{"2021":{"01":{"4":{"2":3},"5":{"2":3},"6":{"2":3}}},"2022":{"01":{"4":{"2":3},"5":{"2":3},"6":{"2":3}}}}

Upvotes: 1

Related Questions