Icare
Icare

Reputation: 1371

How to deal with that kind of json?

The backend returns this kind of json:

UPDATED: 2018-12-27

{
  "3dfb71719a11693760f91f26f4f79c3c": {
    "a-type": {
      "var1": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      "var2": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      }
    },
    "b-type": {
      "var3": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
    },
    "c-type": {
      "var4": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
    }
  },
  "c91891522a8016fc8a097b9e405b118a": {
    "a-type": {
      "var1": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      "var2": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
    },
    "b-type": {
      "var3": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
    },
    "c-type": {
      "var4": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
    }
  }
}

The first parameter, is a unique key. I wanted to take some inspiration from this nice blog from Poojã Bhaumik (https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51), but not sure how to deal with the above json. In fact, is more about the first unique key that I don't know how to deal with it.

Another thing. I would like to use 'flutter packages pub run build_runner build' command to generate the .g.dart file like explained here

Would you mind to give me some hint?

Thanks

Upvotes: 0

Views: 77

Answers (1)

Miguel Ruivo
Miguel Ruivo

Reputation: 17756

If I understand clear, your problem is that the keys from that map will be randomly unique ID’s.

You can pick your keySet and then loop for each key to create each object and it’s own nested objects. Something like this:

void main(){

  Map<String, dynamic> map = json.decode('yourBodyResponse');
  List<MyObject> myObjects = List<MyObject>();

  final keys = map.keys;

  keys.forEach((id){
    final MyObject obj = MyObject.fromJson(id, map[id]); 
    myObjects.add(obj);
  });

}

class ABC {

  final String value;
  final int time;

  ABC({this.value, this.time});

}

class Def { 

  final String value;
  final int time;

  Def({this.value, this.time});

}

class MyObject {

  final String id;
  final ABC abc;
  final Def def;

  MyObject({this.id,
            this.abc,
            this.def
           });


factory MyObject.fromJson(String id, Map<String, dynamic> json){
    return MyObject(
      id: id,
      abc: ABC(
        value: json['abc']['value'],
        time: json['abc']['time']),
      def: Def(
        value: json['def']['value'], 
        time: json['def']['time']),
    );
}

}

Disclaimer: I’ve created the code on my phone with DartPad, although it should be fine, might not be well formated, miss a bracket or have a typo.

Upvotes: 1

Related Questions