I have this JSON file I want to fetch "name" field but I a have not better understanding about JSON file can anyone please explain how can I read this JOSN file format and How can I access "name" field to print. I have tried multiple code but I did not make it successful.
{
"stream": {
"tv": [{
"name": "Tv",
"description": "Tv",
"url": "this is the url",
"image": "imagelink",
}]
}
}
Here is the Code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(HomePage());
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List data=[];
@override
void initState() {
fetchData();
super.initState();
}
void fetchData() async {
final response =
await http.get('Link here');
if (response.statusCode == 200) {
setState(() {
data = json.decode(response.body);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Text(data[0]["stream"]["adomtv"][0]["name"]),// how can I access given Json fields here
)
);
}
}
So I have tried this:
import 'dart:convert';
main() {
String jsonS = """{
"stream": {
"tv": [{
"name": "Tv",
"description": "Tv",
"url": "this is the url",
"image": "imagelink"
}]
}
}""";
var myMap = json.decode(jsonS);
var myName = myMap['stream']['tv'][0]['name'];
print('${myName}');
}
This works as expected and produces the name of the Tv.
However, I think you have a typo in your json. My guess is that you are getting a stream of objects, one of which is the Tv. So I would expect your json to look more like:
{
"stream": { [
{
"name": "Tv",
"description": "Tv",
"url": "this is the url",
"image": "imagelink"
},
{
"name": "Radio",
"description": "Radio",
"url": "this is the url",
"image": "imagelink"
},
]}
If that is the case you just need data['stream'][0]['name'] for the TV and data['stream'[1]['name'] for the radio. So my advice is check the server data stream carefully.
Hope this helps.
Look you have list type data List data=[];
that require the index in integer value so if you have it as string you can use the way you want. If you want to access it like this and you are handle the JSON as well than convert JSON a little bit
{
"stream": {
"tv": [{
"name": "Tv",
"description": "Tv",
"url": "this is the url",
"image": "imagelink",
}]
}
}
Convert it into
[
{
"stream": {
"tv": [{
"name": "Tv",
"description": "Tv",
"url": "this is the url",
"image": "imagelink",
}]
}
}
]
Now you can access the way you are want. this will work for you know data[0]["stream"]["adomtv"][0]["name"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With