Home > OS >  How create dynamic json model
How create dynamic json model

Time:02-01

how can I make a dynamic JSON model for this Josn, all keys are dynamic like "Large,X-Larg, Red, Blue", only the key optionDisplayValues is

{
   "optionDisplayValues":{
      "Large":{
         "value":"Large",
         "displayType":"text"
      },
      "X-Larg":{
         "value":"X-Larg",
         "displayType":"text"
      },
      "Red":{
         "value":"#7d4141",
         "displayType":"color"
      },
      "Blue":{
         "value":"#25a953",
         "displayType":"color"
      }
   }
}

CodePudding user response:

You can go to this link, and you can paste your json there.

Then after that, you can name your class whatever you want and click on the Generate button. It will generate the model for you.

There are also plugins available for both Android studio and VS code for converting JSON to dart.

CodePudding user response:

Each dynamic item should be represented as Map<DisplayValue>, so:

DisplayValue should be:

class DisplayValue {
String value;
String displayText;
}

And your collection should be:

class MyDataCollection {
Map<String,DisplayValue> optionDisplayValues;
}

To generate toJson and fromJson method use json_serializable plugin: https://pub.dev/packages/json_serializable

You will also need to generate constructors and put json annotations/methods as required by that lib.

  • Related