0

This is the JSON Response I'm getting. I want to Parse the text which says "url" (With. I want to Get this Text)

{
    "data": [
        {
            "id": 1,
            "attributes": {
              "Title": "My Story",
              "Story": "My story is about my life",
              "Image": {
                "data": {
                 "id": 1,
                   "attributes": {
                      "name": "lifeImage.jpeg",
                        "alternativeText": "lifeImage.jpeg",
                         "caption": "lifeImage.jpeg",
                         "url": "/uploads/lifeImage_0e9293ee8d.jpeg", <-- I want to Get this Text
                            "previewUrl": null,
                            "provider": "local"
                        }
                    }
                }
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 3
        }
    }
}

I easily parsed the Title, Story with the Below Dart File. But I'm not sure how can I parse the URL text (One with arrow marks says "<-- I want to Get this Text"). Since it's nested one I don't know how to do that. Please help me with this. Thanks

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';

import 'StoryPage.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Stories',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const Homepage(),
    );
  }
}

class Homepage extends StatefulWidget {
  const Homepage({Key? key}) : super(key: key);

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
  Future<List<Story>> _getStories() async {
    var response = await http.get(Uri.parse(
        'https://exampleapi.com/api/stories/?populate=Image'));
    if (response.statusCode == 200) {
      Map responseData = jsonDecode(response.body);

      List StoriesList = responseData["data"];
      List<Story> stories = [];
      for (var storyMap in StoriesList) {
        stories.add(Story.fromJson(storyMap["attributes"]));
      }
      return stories;
    } else {
      throw Exception('Failed to load stories');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My Stories'),
      ),
      body: Container(
        child: FutureBuilder(
          future: _getStories(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    child: Card(
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              snapshot.data[index].title,
                              style: TextStyle(
                                fontSize: 18.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    onTap: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new StoryPage(
                                    snapshot.data[index],
                                    title: snapshot.data[index].title,
                                    body: snapshot.data[index].body,
                                  )));
                    },
                  );
                },
              );
            }
          },
        ),
      ),
    );
  }
}

class Story {
  final String title;
  final String body;

  Story({required this.title, required this.body});

  factory Story.fromJson(Map<String, dynamic> json) {
    return Story(
      title: json['Title'],
      body: json['Story'],
    );
  }
}

3 Answers 3

1

You can simply parse them like this:

final url = json['image']?['data']?['attributes']?['url'];

here we're using question marks (?) in between, because we're not sure that each element is not null, for example, the data under image may be null, so by using question marks, we're staying safe from null exceptions.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your suggestion :)
also, this is not a way i would suggest doing this, i suggest creating models for each layer and making a fromJson method for each one, etc.
Can you give some example? I'm new to Flutter.
please take a look at this tutorial
1

I took @Adnan approach and modified it little.

final ImageURL = json['Image']?['data']?['attributes']?['url'] ?? ''

Thanks to GitHub Co-Pilot.

Comments

0

I suggest using this website to generate dart or any other language object from json. you just need to covert it to null safety.

here a example:

class AnswerResponse {
  AnswerResponse({
    required this.id,
    required this.description,
    required this.isAccepted,
    required this.isMine,
    required this.media,
    required this.caseId,
    required this.voteUp,
    required this.voteDown,
    required this.votes,
    required this.user,
    required this.comment,
    required this.createdAt,
  });

  factory AnswerResponse.fromJson(final String str) => AnswerResponse.fromMap(json.decode(str));

  factory AnswerResponse.fromMap(final Map<String, dynamic> json) => AnswerResponse(
    id: json["id"],
    description: json["description"],
    isAccepted: json["isAccepted"],
    isMine: json["isMine"],
    media: json["media"] == null ? null : List<MediaResponse>.from(json["media"].map((final dynamic x) => MediaResponse.fromMap(x))),
    caseId: json["caseId"],
    voteUp: json["voteUp"],
    voteDown: json["voteDown"],
    votes: json["votes"],
    user: json["user"] == null ? null : ProfileResponse.fromMap(json["user"]),
    comment: json["comment"] == null ? null : List<CommentResponse>.from(json["comment"].map((final dynamic x) => CommentResponse.fromMap(x))),
    createdAt: json["createdAt"],
  );

  final int? id;
  final int? caseId;
  final int? votes;
  final bool? isAccepted;
  final bool? isMine;
  final bool? voteUp;
  final bool? voteDown;
  final String? description;
  final String? createdAt;
  final ProfileResponse? user;
  final List<MediaResponse>? media;
  final List<CommentResponse>? comment;
}

and to convert json string to dart object:

var data = AnswerResponse.fromMap(jsonString)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.