Santiago G
Santiago G

Reputation: 64

How can I parse this json with a model in Dart?

I need to parse this json with a model, but i don't know how, can someone help me please?

{
    "onboarding" : [
        {
            "image" : "assetsblablabla",
            "title" : "Your favorite delivery",
            "subtitle" : "We got over 200 afiliated commerces for you"
        },
        {
            "image" : "assets sdidj",
            "title" : "Lorem ipsum dolor sit amet",
            "texto_2" : ":0"
        },
        {
            "image" : "assets/uwu/owo",
            "title" : "Service on demand",
            "subtitle" : "Lorem ipsum dolor sit amet"
        }
    ]
}

Upvotes: 0

Views: 55

Answers (1)

RukshanJS
RukshanJS

Reputation: 966

Define your model as ("TestModel" is the arbitrary name I have used),

class TestModel {
  var onboarding;

  TestModel.fromJson(Map json) {
    this.onboarding = json['onboarding'];
  }
}

Then parse it as,

Widget build(BuildContext context) {
    var json = {
      "onboarding": [
        {
          "image": "assetsblablabla",
          "title": "Your favorite delivery",
          "subtitle": "We got over 200 afiliated commerces for you"
        },
        {
          "image": "assets sdidj",
          "title": "Lorem ipsum dolor sit amet",
          "texto_2": ":0"
        },
        {
          "image": "assets/uwu/owo",
          "title": "Service on demand",
          "subtitle": "Lorem ipsum dolor sit amet"
        }
      ]
    };
    var fromTheModel = new TestModel.fromJson(json);
    return Text(fromTheModel.onboarding[0]['image']); //displays "assetsblablabla" 
  }

The last line is obviously an example. You can replace the index [0] as well as the ['image'] according to your specific cases.

Is this what you are looking for?

Upvotes: 1

Related Questions