Flutter Dart Parsing Json Strings into Objects - json

Sup! So my problem is, my Dashboard Model isnt getting data assigned from the json string parsed.Basically Dashboard.userActivity and Dashboard.appName are NULL when i print into console. I cant realy get behind why. the testDataFunction should print the corresponding Dashboard Object with all their data (2 nested classes Performance and UserActivity and 3 variables errors, appname,time.
I did not include the code of Perf and UserAct. as its the same as Dashboard with toJson and fromJson helper Methods.
What did i oversaw? Much thanks in advance!
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class Dashboard {
UserActivity? userActivity; ///class
int? totalError;
Performance? performance; ///class
String? appName;
String? time;
Dashboard(
{this.userActivity,
this.totalError,
this.performance,
this.appName,
this.time});
Dashboard.fromJson(Map<dynamic, dynamic> json) {
userActivity = json['userActivity'] != null
? new UserActivity.fromJson(json['userActivity'])
: null;
totalError = json['totalError'];
performance = json['performance'] != null
? new Performance.fromJson(json['performance'])
: null;
appName = json['appName'];
time = json['time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.userActivity != null) {
data['userActivity'] = this.userActivity!.toJson();
}
data['totalError'] = this.totalError;
if (this.performance != null) {
data['performance'] = this.performance!.toJson();
}
data['appName'] = this.appName;
data['time'] = this.time;
return data;
}
#override
toString() {
return "userActivity: " + userActivity.toString() + ", appName: " + appName!;
}
}
Future testDataFunktion() async {
String backendjsondata = '{"dashboard":{"userActivity":{"total":17,"logins":50,"active":1,"inactive":5,"loginsPerHourLst":[0,0,0,0,0,0,0,4,11,13,3,3,0,0,10,6],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"online":6},"totalError":1,"performance":{"loadTimePagesLst":[583,289,154,105,16,13,4,583,0,0],"totalPageViewsPerHourLst":[0,0,0,0,0,0,0,14,82,104,52,85,9,89,114,34],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"totalPageViews":583},"appName":"intranet","time":"January, 24 2022 15:50:48"}}';
Map<String, dynamic> data = jsonDecode(backendjsondata);
Dashboard dashboard = Dashboard.fromJson(data);
print(dashboard);

Try:
Future testDataFunktion() async {
String backendjsondata = '{"dashboard":{"userActivity":{"total":17,"logins":50,"active":1,"inactive":5,"loginsPerHourLst":[0,0,0,0,0,0,0,4,11,13,3,3,0,0,10,6],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"online":6},"totalError":1,"performance":{"loadTimePagesLst":[583,289,154,105,16,13,4,583,0,0],"totalPageViewsPerHourLst":[0,0,0,0,0,0,0,14,82,104,52,85,9,89,114,34],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"totalPageViews":583},"appName":"intranet","time":"January, 24 2022 15:50:48"}}';
Dashboard dashboard = Dashboard.fromJson(Map.from(jsonDecode(backendjsondata)));
print(dashboard);
}

Related

flutter json decode and file append not working on second run

I was wondering if someone could help? I'm trying to load a file with json content, decode it, convert to a model/object add another element.
The way I'm trying to do this is as follows:
Flow 1: Check file exists = true -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
Flow 2: Check file exists = false -> create file -> add a json template -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
This is working on the first run (flow 1), it'll create the file, add the template then add the first new element. However, when I run it a second time (flow 2), I always get an throwback.
As we speak with the code below, the error is:
E/flutter (13140): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
E/flutter (13140): #0 FileController.writeSingleResponseToFile (package:reefcommander/controllers/FileController.dart:33:39)
E/flutter (13140): <asynchronous suspension>
E/flutter (13140):
This is the code I'm using.
FileController.dart
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:reefcommander/models/ReadingsData.dart';
import 'package:reefcommander/models/SingleDataReqResponse.dart';
import 'dart:convert';
class FileController {
static String date = DateFormat("dd-MM-yyyy").format(DateTime.now());
static String template =
'{"name": "_NAME_", "friendlyName": "_FNAME_", "results": []}';
static final Map<String, String> nameDefenitions = {
'ec': 'EC',
'ph': 'pH',
'atoDayRate': 'Evap Rate',
'sumpTemp': 'Temp (sump)',
'tankTemp': 'Temp (tank)'
};
static Future<File> checkFileExists(String type) async {
readFile(type);
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
return file;
}
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
var r = Map<String, dynamic>.from(jsonDecode(await file.readAsString()));
print(r.runtimeType);
ReadingsData existingdata = ReadingsData.fromJson(r[0]);
//ReadingsData existingdata =
// r.map<ReadingsData>((json) => ReadingsData.fromJson(json));
print(existingdata);
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
print('DATA: ${existingdata.toJson().toString()}');
file.writeAsString(jsonEncode(existingdata.toJson().toString()));
}
static Future<void> deleteFile(String type) async {
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
await file.delete();
} else {}
} catch (e) {
// Error in getting access to the file.
}
}
static Future<String> readFile(String type) async {
String text = '';
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
text = await file.readAsString();
} else {
file.create(recursive: true);
String tempbase = template;
String write = tempbase
.replaceAll('_NAME_', type.toString())
.replaceAll('_FNAME_', nameDefenitions[type]!);
await file.writeAsString(write);
text = await file.readAsString();
}
} catch (e) {
print("Read error");
}
return text;
}
}
ReadingsData.dart
import 'dart:convert';
class ReadingsData {
String? name;
String? friendlyName;
List<Results>? results;
ReadingsData(
{required this.name, required this.friendlyName, required this.results});
ReadingsData.fromJson(Map<String, dynamic> json) {
name = json['name'];
friendlyName = json['friendlyName'];
if (json['results'] != null) {
results = <Results>[];
json['results'].forEach((v) {
results!.add(Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['friendlyName'] = friendlyName;
if (results != null) {
data['results'] = results!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String? stamp;
String? value;
Results({required this.stamp, required this.value});
Results.fromJson(Map<String, dynamic> json) {
stamp = json['stamp'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['stamp'] = stamp;
data['value'] = value;
return data;
}
}
Test code
FileController.writeSingleResponseToFile(
SingleDataReqResponse(name: "test", stamp: "10:22:00", value: "2222"));
For anyone else in my situation, I've resolved it. Solution below.
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
ReadingsData existingdata =
ReadingsData.fromJson(jsonDecode(await file.readAsString()));
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
file.writeAsString(jsonEncode(existingdata.toJson()));
}

fetching json data and creating a list

I'm currently studying flutter and I'm creating an app on my own...
So the problem at the moment is that I need to fetch json data and to put it in the list, in this case listOfCards (custom made object Card contains initialSearch as String and results as List. I've been following this example https://flutter.dev/docs/cookbook/networking/background-parsing#convert-the-response-into-a-list-of-photos but there they are directly parsing data into app and I really didn't know how to use it in my case.
I need to fill this listOfCards List to use it later in the app.
So here's the code:
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
List<Card> listOfCards = [];
Future<List<Card>> fetchCards(http.Client client) async {
final response = await client.get(
Uri.parse('605a2f18b11aba001745dbdd.mockapi.io/api/v1/cards'),
);
return parseCards(response.body);
}
List<Card> parseCards(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Card>((json) => Card.fromJson(json)).toList();
}
class Card {
String initialSearch;
List<String> mostPopularSearches;
Card({
this.initialSearch,
this.mostPopularSearches,
});
factory Card.fromJson(Map<String, dynamic> json) {
return Card(
initialSearch: json['search'] as String,
mostPopularSearches: json['results'] as List,
);
}
}
Custome class
class Card {
String initialSearch;
List<String> mostPopularSearches;
Card({this.initialSearch, this.mostPopularSearches});
Card.fromJson(Map<String, dynamic> json) {
initialSearch = json['initialSearch'];
mostPopularSearches = json['mostPopularSearches'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['initialSearch'] = this.initialSearch;
data['mostPopularSearches'] = this.mostPopularSearches;
return data;
}
}
Generated using Json to dart
To store the responses as Card object
Card _card = Card.fromJson(responsebody);
Your response JSON
{
"initialSearch": "Google",
"mostPopularSearches": [
"Google",
"Facebook",
"Stacjoverflow",
"Reddit"
]
}

Error: type 'String' is not a subtype of type 'List<dynamic>'

I want to fetch dat form some API and parse its data to model.
MyModel:
class SetupIdeaModel {
String id;
String userId;
String typeIdea = "Implemented Idea";
String category; //Or Industry
String experienceYear;
String experienceMonth;
String ideaHeadline;
String ideaText;
Map timeline = {
"timelineType": "date",
"details": null,
};
List documents = [];
Map uploadVideo;
String location;
String estimatedPeople;
Map whitePaper;
bool needServiceProvider = false;
bool needInvestor = true;
}
}
and I fetch data from the API with the getIdeaList method:
getIdeaList method
Future getIdeaList(String token) async {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
//Parsing ideaList to SetupIdeaModel
ideas = List();
try {
(response.data as List).forEach((element) {
SetupIdeaModel idea = new SetupIdeaModel();
var months = int.parse(element["industryExperienceInMonth"]);
var year = (months / 12).floor();
var remainderMonths = months % 12;
print("$year year and $remainderMonths months");
idea.id = element["_id"];
idea.userId = element["userId"];
idea.typeIdea = element["ideaType"];
idea.category = element["industry"];
idea.experienceYear = year.toString();
idea.experienceMonth = remainderMonths.toString();
idea.ideaHeadline = element["headline"];
idea.ideaText = element["idea"];
idea.estimatedPeople = element["estimatedPeople"].toString();
print("Documents ${element["uploadDocuments"]}");
idea.location = element["targetAudience"];
idea.documents = element["uploadDocuments"];
// idea.timeline = element["timeline"];
// idea.uploadVideo = element["uploadVideo"];
ideas.add(idea);
});
} catch (e) {
print("Error: $e");
}
print("ideas $ideas");
notifyListeners();
}
Everything is OK but When I add one of these line:
idea.documents = element["uploadDocuments"];
idea.timeline = element["timeline"];
idea.uploadVideo = element["uploadVideo"];
I have got the error.
The data comes for the API is like this:
[
{
"industryExperienceInMonth":30,
"estimatedPeople":200,
"needServiceProvider":true,
"needInvestor":true,
"_id":5fcc681fc5b4260011810112,
"userId":5fb6650eacc60d0011910a9b,
"ideaType":"Implemented Idea",
"industry":"Technalogy",
"headline":"IDea headline",
"idea":"This is aobut your idea",
"timeline":{
"timelineType":"date",
"details":{
"date":Dec 6,
2020
}
},
"uploadDocuments":[
{
"_id":5fcc6804c5b4260011810110,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/document/741333-beats_by_dre-wallpaper-1366x768.jpg
}
],
"uploadVideo":{
"_id":5fcc681ac5b4260011810111,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/video/588700-beats_by_dre-wallpaper-1366x768.jpg
},
"targetAudience":"heart",
"__v":0
}
]
I'm using Dio package.
The documents in the model is a list and the uploadDocuments the come form API is a list too. But Why I got this error.
Your JSON data has some syntax errors that's why it's not working. All the UIDs and URLs should be in string format and you should Serializing JSON inside model classes. see also
I have fix some error in your code and did some improvement :
Future getIdeaList(String token) async {
List<SetupIdeaModel> setupIdeaModel = List();
try {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
if (response.statusCode == 200) {
List<SetupIdeaModel> apiData = (json.decode(utf8.decode(response.data)) as List)
.map((data) => new SetupIdeaModel.fromJson(data))
.toList();
setupIdeaModel.addAll(apiData);
}
} catch (e) {
print("Error: $e");
}
}
This is the model class :
class SetupIdeaModel {
int industryExperienceInMonth;
int estimatedPeople;
bool needServiceProvider;
bool needInvestor;
String sId;
String userId;
String ideaType;
String industry;
String headline;
String idea;
Timeline timeline;
List<UploadDocuments> uploadDocuments;
UploadDocuments uploadVideo;
String targetAudience;
int iV;
SetupIdeaModel(
{this.industryExperienceInMonth,
this.estimatedPeople,
this.needServiceProvider,
this.needInvestor,
this.sId,
this.userId,
this.ideaType,
this.industry,
this.headline,
this.idea,
this.timeline,
this.uploadDocuments,
this.uploadVideo,
this.targetAudience,
this.iV});
SetupIdeaModel.fromJson(Map<String, dynamic> json) {
industryExperienceInMonth = json['industryExperienceInMonth'];
estimatedPeople = json['estimatedPeople'];
needServiceProvider = json['needServiceProvider'];
needInvestor = json['needInvestor'];
sId = json['_id'];
userId = json['userId'];
ideaType = json['ideaType'];
industry = json['industry'];
headline = json['headline'];
idea = json['idea'];
timeline = json['timeline'] != null
? new Timeline.fromJson(json['timeline'])
: null;
if (json['uploadDocuments'] != null) {
uploadDocuments = new List<UploadDocuments>();
json['uploadDocuments'].forEach((v) {
uploadDocuments.add(new UploadDocuments.fromJson(v));
});
}
uploadVideo = json['uploadVideo'] != null
? new UploadDocuments.fromJson(json['uploadVideo'])
: null;
targetAudience = json['targetAudience'];
iV = json['__v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['industryExperienceInMonth'] = this.industryExperienceInMonth;
data['estimatedPeople'] = this.estimatedPeople;
data['needServiceProvider'] = this.needServiceProvider;
data['needInvestor'] = this.needInvestor;
data['_id'] = this.sId;
data['userId'] = this.userId;
data['ideaType'] = this.ideaType;
data['industry'] = this.industry;
data['headline'] = this.headline;
data['idea'] = this.idea;
if (this.timeline != null) {
data['timeline'] = this.timeline.toJson();
}
if (this.uploadDocuments != null) {
data['uploadDocuments'] =
this.uploadDocuments.map((v) => v.toJson()).toList();
}
if (this.uploadVideo != null) {
data['uploadVideo'] = this.uploadVideo.toJson();
}
data['targetAudience'] = this.targetAudience;
data['__v'] = this.iV;
return data;
}
}
class Timeline {
String timelineType;
Details details;
Timeline({this.timelineType, this.details});
Timeline.fromJson(Map<String, dynamic> json) {
timelineType = json['timelineType'];
details =
json['details'] != null ? new Details.fromJson(json['details']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['timelineType'] = this.timelineType;
if (this.details != null) {
data['details'] = this.details.toJson();
}
return data;
}
}
class Details {
String date;
Details({this.date});
Details.fromJson(Map<String, dynamic> json) {
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
return data;
}
}
class UploadDocuments {
String sId;
String uriPath;
UploadDocuments({this.sId, this.uriPath});
UploadDocuments.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
uriPath = json['uriPath'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['uriPath'] = this.uriPath;
return data;
}
}

how to filx Unexpected character (at char 1) in flutter

hy we have a radio server with the followoing json file
{
"icestats":{
"admin":"icemaster#localhost",
"host":"online.localhost.be",
"location":"Earth",
"server_id":"Icecast 2.4.4",
"server_start":"Sun, 30 Aug 2020 10:50:52 +0200",
"server_start_iso8601":"2020-08-30T10:50:52+0200",
"source":[
{
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/mp3_320",
"server_description":"Very Oldies!",
"server_name":"loclahost",
"server_type":"audio/mpeg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"title":"1951: Four Knights - I Love The Sunshine Of Your Smile",
"dummy":null
},
{
"audio_bitrate":320000,
"audio_channels":2,
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"audio_samplerate":44100,
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/ogg_320",
"server_description":"Very Oldies!",
"server_name":"localhost",
"server_type":"application/ogg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"subtype":"Vorbis",
"dummy":null
}
]
}
}
if io parse this with this model i get the error 'unexpected charcater at 1'
class Autogenerated {
Icestats icestats;
Autogenerated({this.icestats});
Autogenerated.fromJson(Map<String, dynamic> json) {
icestats = json['icestats'] != null
? new Icestats.fromJson(json['icestats'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.icestats != null) {
data['icestats'] = this.icestats.toJson();
}
return data;
}
}
class Icestats {
String admin;
String host;
String location;
String serverId;
String serverStart;
String serverStartIso8601;
List<Source> source;
Icestats(
{this.admin,
this.host,
this.location,
this.serverId,
this.serverStart,
this.serverStartIso8601,
this.source});
Icestats.fromJson(Map<String, dynamic> json) {
admin = json['admin'];
host = json['host'];
location = json['location'];
serverId = json['server_id'];
serverStart = json['server_start'];
serverStartIso8601 = json['server_start_iso8601'];
if (json['source'] != null) {
source = new List<Source>();
json['source'].forEach((v) {
source.add(new Source.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['admin'] = this.admin;
data['host'] = this.host;
data['location'] = this.location;
data['server_id'] = this.serverId;
data['server_start'] = this.serverStart;
data['server_start_iso8601'] = this.serverStartIso8601;
if (this.source != null) {
data['source'] = this.source.map((v) => v.toJson()).toList();
}
return data;
}
}
class Source {
String audioInfo;
int bitrate;
String genre;
int iceBitrate;
int iceChannels;
int iceSamplerate;
int listenerPeak;
int listeners;
String listenurl;
String serverDescription;
String serverName;
String serverType;
String serverUrl;
String streamStart;
String streamStartIso8601;
String title;
Null dummy;
int audioBitrate;
int audioChannels;
int audioSamplerate;
String subtype;
Source(
{this.audioInfo,
this.bitrate,
this.genre,
this.iceBitrate,
this.iceChannels,
this.iceSamplerate,
this.listenerPeak,
this.listeners,
this.listenurl,
this.serverDescription,
this.serverName,
this.serverType,
this.serverUrl,
this.streamStart,
this.streamStartIso8601,
this.title,
this.dummy,
this.audioBitrate,
this.audioChannels,
this.audioSamplerate,
this.subtype});
Source.fromJson(Map<String, dynamic> json) {
audioInfo = json['audio_info'];
bitrate = json['bitrate'];
genre = json['genre'];
iceBitrate = json['ice-bitrate'];
iceChannels = json['ice-channels'];
iceSamplerate = json['ice-samplerate'];
listenerPeak = json['listener_peak'];
listeners = json['listeners'];
listenurl = json['listenurl'];
serverDescription = json['server_description'];
serverName = json['server_name'];
serverType = json['server_type'];
serverUrl = json['server_url'];
streamStart = json['stream_start'];
streamStartIso8601 = json['stream_start_iso8601'];
title = json['title'];
dummy = json['dummy'];
audioBitrate = json['audio_bitrate'];
audioChannels = json['audio_channels'];
audioSamplerate = json['audio_samplerate'];
subtype = json['subtype'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['audio_info'] = this.audioInfo;
data['bitrate'] = this.bitrate;
data['genre'] = this.genre;
data['ice-bitrate'] = this.iceBitrate;
data['ice-channels'] = this.iceChannels;
data['ice-samplerate'] = this.iceSamplerate;
data['listener_peak'] = this.listenerPeak;
data['listeners'] = this.listeners;
data['listenurl'] = this.listenurl;
data['server_description'] = this.serverDescription;
data['server_name'] = this.serverName;
data['server_type'] = this.serverType;
data['server_url'] = this.serverUrl;
data['stream_start'] = this.streamStart;
data['stream_start_iso8601'] = this.streamStartIso8601;
data['title'] = this.title;
data['dummy'] = this.dummy;
data['audio_bitrate'] = this.audioBitrate;
data['audio_channels'] = this.audioChannels;
data['audio_samplerate'] = this.audioSamplerate;
data['subtype'] = this.subtype;
return data;
}
}
the code i have used i pretty simple this is the code i have used.
if i parse the same code with a simple xml structure this works but with the icecast parsing this does not succeed.
please advice me
var JsonData = 'http://127.0.0.1:8000/status-json.xsl';
var parsedJson = json.decode(JsonData);
var title = Source.fromJson(parsedJson);
is the json formatting of the icecast server incorrect ? it starts with a {
update 1
class User {
String title;
User(Map<String, dynamic> data){
title = data['title'];
}
}
Future<Source> fetchData() async{
var jsonData = 'http://online.doobeedoo.be:8000/status-json.xsl';
final response =
await http.get(jsonData); //wacht to de data is ontvangen (200)
if(response.statusCode == 200)
{
var parsedJson = json.decode(response.body); //parsen van response
var user = User(parsedJson);
return('${user.title}'); //error here (A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'.)
}
else
{
throw Exception('Failed to load status.json response file');
}
}
Use the http package to make a request to your server and retrieve a response. Then parse the JSON the way your currently have it. You're currently parsing a String URL. Not a JSON.
import 'package:http/http.dart' as http;
var url = 'http://127.0.0.1:8000/status-json.xsl';
var response = await http.get(url);//Actually get the data at the URL
var parsedJson = json.decode(response.body);//Parse the response
var title = Source.fromJson(parsedJson);

Flutter parsing JSON with array

I have troubles with parsing a JSON file with array.
It looks like something like this:
{
"status": "200",
"addresses": [
{
"address": "Address 1"
},
{
"address": "Address 2"
}
]
}
And I tried to parse it with:
var response = jsonDecode(res.body);
print(response['addresses']['address'][0]);
print(response['addresses']['address'][1]);
But it is not working. Is there any common pattern how this should be?
That's because you're not accessing it the right way. You have a Map<String,dynamic> that has a List<Map<String,String>> for the key addresses.
If you want to access the first two elements of that list, you can do it by doing:
var response = jsonDecode(res.body);
print(response['addresses'][0]['address']);
print(response['addresses'][1]['address']);
The easiest way I have found for dealing with this is to have this website write the JSON parser for me. Simply copy / paste you JSON into provide field and choose Dart as the language:
https://app.Quicktype.io
Your best mapping the data into a class there is a useful website (created by Javier Lecuona) that generates the class for you. https://javiercbk.github.io/json_to_dart/
Here is an example:
var parsedJson = jsonDecode(json);
var addressList = ClientAddresses.fromJson(parsedJson);
print(addressList.addresses[0].address);
print(addressList.addresses[1].address);
class ClientAddresses {
String status;
List<Addresses> addresses;
ClientAddresses({this.status, this.addresses});
ClientAddresses.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['addresses'] != null) {
addresses = new List<Addresses>();
json['addresses'].forEach((v) {
addresses.add(new Addresses.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.addresses != null) {
data['addresses'] = this.addresses.map((v) => v.toJson()).toList();
}
return data;
}
}
class Addresses {
String address;
Addresses({this.address});
Addresses.fromJson(Map<String, dynamic> json) {
address = json['address'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['address'] = this.address;
return data;
}
}