3

I'm new in this http and JSON world, so I may be wrong on stating or naming some terms. I'm getting a course from Udemy and I'm trying to get a specific object or that object's property. But whatever I do, I'm still fetching all the data, instead of an index.

Here's my code:

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

class JsonParsingSimple extends StatefulWidget {

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

class _JsonParsingSimpleState extends State<JsonParsingSimple> {
  Future data;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    data = getData();
  }

{...}

  Future getData() async
  {
    Future data;
    String url = "https://jsonplaceholder.typicode.com/posts";
    Network network = Network(url);

    data = network.fetchData();
    data.then((value)
    {
      print(value[0]['title']); //this line still brings me every data like i'm writing *(value)*
    });
    
    return data; 
  }
}

class Network
{
  final String url;
  Network(this.url);

  Future fetchData() async
  {
    print("$url");
    Response response = await get(Uri.parse(url));

    if(response.statusCode == 200)
    {
      print(response.body);
      return json.decode(response.body); 
    }
    else
    {
      print(response.statusCode);
    }
  }
  
}

print(value) or print(value[0]) or print(value[0]['id']). They're all giving the same. Fetching everything.

2
  • Delete print(response.body); If you need 1 post only then you should use: https://jsonplaceholder.typicode.com/posts/<any_ID> instead Commented Jul 7, 2021 at 15:24
  • @ΟυιλιαμΑρκευα hahahah you're right. The moment I deleted the print(response.body) line, everything worked fine. Thanks. Commented Jul 7, 2021 at 18:14

2 Answers 2

2

https://jsonplaceholder.typicode.com/posts, providing a list of JSON objects, so basically, we first need to parse them, follow the below example it shows how to create an object and parse it to list.

import 'dart:convert';

import 'package:http/http.dart' as http;

void main() async {
  String url =
      "https://jsonplaceholder.typicode.com/posts";
  final response = await http.get(Uri.parse(url));
  List<JsonData> list = [];
  for(var data in jsonDecode(response.body) as List) {
    list.add(JsonData.fromJson(data));
  }
  print(list[0].id); // Pass the index to get specific values from model
}

class JsonData {
  int? userId;
  int? id;
  String? title;
  String? body;

  JsonData({this.userId, this.id, this.title, this.body});

  JsonData.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['userId'] = this.userId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['body'] = this.body;
    return data;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The most basic way is to import dart: convert library;


for example, you have data like

{
  "student": {
      "name": "Robin",
      "subject": "computer"
   }
}
import 'dart:convert';

Map<String, dynamic> user = jsonDecode(jsonString);
var name = user['student']['name'];

For simple data the above way is correct, but for more complex data I would recommend using a package or do check it out the below given

You may use this https://app.quicktype.io/ by choosing the language as a dart.
for converting complex JSON data to dart objects. And later using those objects to get the particular value you want

// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'dart:convert';

class Welcome {
    Welcome({
        this.student,
    });

    Student student;

    factory Welcome.fromRawJson(String str) => Welcome.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        student: Student.fromJson(json["student"]),
    );

    Map<String, dynamic> toJson() => {
        "student": student.toJson(),
    };
}

class Student {
    Student({
        this.name,
        this.subject,
    });

    String name;
    String subject;

    factory Student.fromRawJson(String str) => Student.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Student.fromJson(Map<String, dynamic> json) => Student(
        name: json["name"],
        subject: json["subject"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
        "subject": subject,
    };
}

The above-given code helps you to convert JSON data to object and vice versa, if you need to send it through an API

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.