So I tried to follow the photo example for flutter JSON - the example works but when I tried to exit the JSON http://api.radiomedia.com.au/api-access/news I ran into an issue which the example does not cover. It's the start of the JSON string
{"news":[{
I am wondering if anyone has a list view example that prints data from a complex JSONP example
{
"news": [
{
"_id": "5d71dbff34eb1563bff1ac87",
"title": "Billie Eilish All Good Girls Go To Hell (Music Video Review)",
"keywords": "Billie Eilish, All Good Girls Go To Hell, Music Video, Review",
"description": "We review Billie Eilish has just released the music video to the much waited fan fair for All Good Girls Go To Hell.",
"image": "https://storage.googleapis.com/radiomedia-images/news/BEAllGoodGirlsGoToHell.jpg",
"url": "billie_eilish_all_good_girls_go_to_hell_review",
"category": "Review,Music Video",
"author": "Russell Harrower",
"content": "Billie Eilish has just released the music video to the much waited fan fair for All Good Girls Go To Hell.\n\nThe music video which features Billie Eilish opens with an angel falling from the heaven above, then lands in what seems to be tar like substance which Billie slowly drags her body out of.\n\nWhat makes this one of the most interesting music videos I have seen for a long time, is the special effects that had to be used towards the end of the video, where the angel wings seem to turn to bat like wings.\n\nWhile this is only being really picky, you will notice either the quality of the special effects budget might of all been used up in the first half of the video as the bat like wings don't stay centered as she walks away from the camera. But that's just me being REALLY PICKY. The song itself is one of struggle and a song I feel we all can realate to in one way or another. Checkout the video below.",
"youtube": "-PZsSWwc9xA",
"TweetIDs": [],
"timestamp": "2019-09-06T21:08:20.201Z",
"published": true
},
{
"_id": "5d6f9cd134eb1563bff06171",
"title": "Inferno Engulfs Conception",
"keywords": "Magpie, Cyclists Attacked, Bella Visita Syndey",
"description": "Complaint by a cyclists saying that she was “attacked” by a magpie while riding her bike in Bella Vista Sydney resulted in the Hills District Council telling her the magpie had been “removed“",
"image": "https://storage.googleapis.com/radiomedia-images/news/Boatonfire.jpg",
"url": "inferno_engulfs_conception",
"category": "America,L.A",
"author": "Jo-anne Reay-Harrower",
"content": "Dozens are feared dead after a fire swept through a dive boat overnight off the Southern Californian Coast.\n\nFour bodies have been recovered with injuries consistent to drowning according to Coast Guard Lieutenant Commander Mather Kroll.\n\nThe vessel known as the Conception burst into flames around 3am Monday morning (local time) and searchers are still looking for more than two dozen people. It is believed there were 39 people on board of which 5 were crew members that dived into the water soon after the fire started at dawn.\n\n“The crew was actually already awake and on the bridge and they off” said Rochester. Coast Guard Petty Officer Mark Barney has stated that two have suffered minor injuries. 34 other people were asleep below deck when the fire started and it is feared that they may not have been able to escape.\n\nWhen the fire began a distress call was made to the Coast Guard, parts of the message were inaudible but a man was heard saying “ Mayday Mayday… I can’t breathe.”\n\n“ Can you get back on board and unlock the boat?” a L.A Coast Guard dispatcher asked and followed with asking if there was an “ escape hatch for any of the people onboard”,\n\nThe crew members voice could not be understood when the dispatcher asks “ You don’t have any firefighting gear at all? No fire extinguishers or anything?”\n\nThe “Great Escape” a vessel that was nearby rescued crew members that jumped from the boat. When queried if the crew had tried to help the others on board Mr Rochester said “ I don’t have any additional information!”\n\nThe Conception was a 20 -metre commercial scuba diving vessel and was on the last day of a labor day week-end cruise to the channel Islands when she was engulfed anchored 18 metres of the Santa Cruz coast her bow is still visible above the waterline as she sank 64 feet.<img src=\"https://storage.googleapis.com/radiomedia-images/news/fire37839.jpg\" alt=\"Firefighter - Santa Cruz coast\">\n\nAccording to the “Truth Aquatics” website the vessel was equipped with rafts and life jackets for up to 110 passengers and exits on the port, starboard and bow that provide “easy water entry”.\n\nRelatives are still waiting to hear news of their loved ones with one woman who was at the harbour saying “my son was on that boat”. While at the same time Mr James Kohl (pictured below) was waiting at the gate waiting on news of his 58 year old brother who was a cook on the Conception.\n\n<img src=\"https://storage.googleapis.com/radiomedia-images/news/oldman-camera.jpg\" alt=\"old man stairing through gate - Santa Cruz coast\">",
"TweetIDs": [],
"timestamp": "2019-09-04T13:21:30.201Z",
"published": true
},
{
"_id": "5d6f981834eb1563bff05f18",
"title": "Council Kills Australian Icon",
"keywords": "Magpie, Cyclists Attacked, Bella Visita Syndey",
"description": "Complaint by a cyclists saying that she was “attacked” by a magpie while riding her bike in Bella Vista Sydney resulted in the Hills District Council telling her the magpie had been “removed“",
"image": "https://storage.googleapis.com/radiomedia-images/news/8859128-3x2-700x467.jpg",
"url": "council_kills_australia_icon",
"category": "Australia,NSW",
"author": "Jo-anne Reay-Harrower",
"content": "A complaint by a cyclists saying that she was “attacked” by a magpie while riding her bike in Bella Vista Sydney resulted in the Hills District Council telling her the magpie had been “removed“.\n\n I have just received an email advising that the magpie had now been removed, so hopefully that area will now be safe” the cyclist wrote on a private face book group. We don’t know if she knew that by “removing”, the magpie that it had actually been killed by t he Council.\n\nThe post caused fury from Animal lovers on other community pages. “I am so angry right now that I won’t even comment,” wrote one person on face book.\n\nThe following is this reporters personal feelings.\n\nIt is Springtime and magpies are nesting, this is when magpies usually swoop because they are protecting their nests and young, surely it is not to hard to avoid an area where you know maggies are nesting during this period.\n\nMaybe if people reported nesting magpies to their local Councils the Councils could place warning signs or even better maybe the person who sees it could make up their own warning sign to warn other people.\n\nWHY IS IT OKAY FOR HUMANS TO PROTECT THEIR YOUNG BUT NOT OTHER CREATURES?",
"TweetIDs": [],
"timestamp": "2019-09-03T13:21:30.201Z",
"published": true
},
{
"_id": "5d6ce55abbe890f60cd1a1e7",
"title": "Third Time Lucky - pilot lands",
"keywords": "trainee pilot, instructor fell unconscious, Chuck Mc Elwee, Robert Mollard ",
"description": "Mr Sylvester told air traffic control “ I’m trying to keep him up but he keeps falling down”, when asked by air traffic control if he knew how to operate the plan Mr Sylvester replied “ This is my third lesson”",
"image": "https://storage.googleapis.com/radiomedia-images/news/cessna.jpg",
"url": "third_time_lucky-pilot_lands",
"category": "Australia,Perth,Air Taffic",
"author": "Jo-anne Reay-Harrower",
"content": "It was third time lucky for a trainee pilot who landed a plane at Jandakot airport on Saturday. The trainee pilot had only had three lessons when his instructor fell unconscious.\n\nMr Sylvester told air traffic control “ I’m trying to keep him up but he keeps falling down”, when asked by air traffic control if he knew how to operate the plan Mr Sylvester replied “ This is my third lesson”.\n\nThe operator then told him “We’re tracking where you are at the moment”. He went on to say \"You're doing a really great job. I know this is really stressful. But you're going to do an amazing job and we're going to help you get down to the ground, OK?\"\n\nThe controller then talked the trainee pilot down which took over 50 minutes. The owner of the flying school Chuck Mc Elwee said \"This could have gone way, way bad,\" he said.\n\n\"But everything worked out right, and it worked right, mostly because of the cooperation of the tower, the fact that he was a student — that he was dedicated and he knew what he was doing and he pulled it off — and that my flight instructor went up to the tower and they all worked together.\"\n\nMr McElwee praised Mr Sylvester’s wife by saying “ She was a rock, let me tell you, she held it together all the way along the line”.\n\nMr Sylvester has received his first flying solo certificate even though this was more than likely not the way he expected to earn it.",
"TweetIDs": [],
"timestamp": "2019-09-02T13:21:30.201Z",
"published": true
},
{
"_id": "5d5bce814456f4ee8926a33c",
"title": "Anchors Away For Ross Lyon",
"keywords": "AFL, Fremantle Dockers Coach Ross Lyon, Ross Lyon Saked",
"description": "Ross Lyon has been sacked as coach for the Fremantle Dockers. President Dale Alcock said in a statement “Fremantle has not made the finals for the past four years. This isn’t acceptable to the board, the players, and most importantly to our supporters.”",
"image": "https://storage.googleapis.com/radiomedia-images/news/rosslyonsaked.jpg",
"url": "anchors-away-for-ross-lyon",
"category": "Australia,AFL,Fremantle Dockers",
"author": "Jo-anne Reay-Harrower",
"content": "Ross Lyon has been sacked as coach for the Fremantle Dockers.\n\nPresident Dale Alcock said in a statement “Fremantle has not made the finals for the past four years. This isn’t acceptable to the board, the players, and most importantly to our supporters.” He went on to say “We need high performance and consistency at all levels of the club, so we need to change and evolve”.\n\nDavid Hale assistant coach will coach the final game of the season.\n\nAlcock went on to say “ Its’ clear for a number of reasons that as a club we haven’t achieved as we should. The board has a duty to act in the best interest of it’s supporters and members. As a result, the club requires a new coach and CEO,…. The search for a new coach and CEO starts today.”",
"TweetIDs": [
"1163660108162691073",
"1163677257644167169",
"1030743767395913728"
],
"timestamp": "2019-08-20T13:21:30.201Z",
"published": true
},
{
"_id": "5d53f99e4456f4ee892318f9",
"title": "Sydney Under Attack",
"keywords": "Sydney Stabbing, Sydney police, Allahu Akbar, clearly dangerous, Emergency services, mental health issues",
"description": "21 year old man balaclava and wielding a large butcher’s knife in the vicinity of King St. He shouted “Allahu Akbar” and challenged police to “fucking shoot me in the head”",
"image": "https://storage.googleapis.com/radiomedia-images/news/Sydney-Stabbing-4.jpg",
"url": "sydney-under-attack",
"category": "Australia,Sydney",
"author": "Peter Bassett-scarfe",
"content": "Sydney police received a call at about 2PM today of a man wearing a balaclava and wielding a large butcher’s knife in the vicinity of King St.\n\nHe shouted “Allahu Akbar” and challenged police to “fucking shoot me in the head”.\n\nHe has since been identified as a 21-year-old man from Marayong.\n\nThe man stabbed a 41-year-old woman in the back in what appears to be a random attack.\n\nThree members of the public engaged and restrained the “clearly dangerous” man, using a chair and a milk crate, near Wynyard railway station.\n\nEmergency services and police responded and the man was soon arrested.\n\nThen police discovered the body of a 21-year-old woman in an apartment on Clarence St.\n\nThe man was found to have terrorist information on a USB drive about mass casualty crimes overseas, including in North America and New Zealand.\n\nHowever he has no known links to terrorist organisations.\n\nPolice said the man had a long history of mental health issues, and they were investigating reports he absconded from a mental health facility in recent days.",
"TweetIDs": [],
"timestamp": "2019-08-14T20:21:30.201Z",
"published": true
},
{
"_id": "5d4d02594456f4ee89200746",
"title": "With Friends Like This...",
"keywords": "Paul Bennet, royal perth hospital, Aaron Premier, home-made bomb, gun",
"description": "Paul Bennet had been spent 10 days at Royal Perth Hospital when he asked his friend Mr Aaron Premier to bring him his “ stuff “ ",
"image": "https://storage.googleapis.com/radiomedia-images/news/royal-perth-hospital.jpg",
"url": "with-friends-like-this",
"category": "Australia,Royal Perth Hospital",
"author": "Jo-anne Reay-Harrower",
"content": "Mr Paul Bennet had been spent 10 days at Royal Perth Hospital when he asked his friend Mr Aaron Premier to bring him his “ stuff “ and his friend took him literally and brought him his suitcases which contained a home-made bomb, a gun and ammunition.\n\nThe hospital had to close three wards while the bomb squad dealt with it, needless to say Mr Paul Bennet was charged.\n\nWith Friends like this you really don’t need enemies.",
"TweetIDs": [],
"timestamp": "2019-08-09T05:19:00.000Z",
"published": true
},
{
"_id": "5d4d01784456f4ee892006d9",
"title": "Papa You Did Wrong",
"keywords": "lock him up, papadrove through red light, berlin bad driver",
"description": "When the operator answered the call the boy told her “ Papadrove twice through the light when it was red- You must lock him up”",
"image": "https://storage.googleapis.com/radiomedia-images/news/trafficmenedited.jpg",
"url": "papa-you-did-wrong",
"category": "Berlin",
"author": "Jo-anne Reay-Harrower",
"content": "A five year old Berlin boy got so cross with his father for running two red lights that he called the emergency number to report him. When the operator answered the call the boy told her “ Papadrove twice through the light when it was red- You must lock him up” . According to a police face book post the officer “ persuaded him to drop his demand that we send a car around”, the operator explained to the boy that the number was to be used for emergiencies only and “enlightened Papa about the road traffic regulations.",
"TweetIDs": [],
"timestamp": "2019-08-09T05:16:00.000Z",
"published": true
},
{
"_id": "5d4cff6f4456f4ee892005cb",
"title": "6Year Old French Tourist Injured",
"keywords": "6 year old, french tourist, thrown tate modern, teen throws kid from tate modern",
"description": "6 year old french tourist currently in a critical condition after being thrown form the tenth story.",
"image": "https://storage.googleapis.com/radiomedia-images/news/6YEAR_OLD_FRENCH_TOURIST_INJURED-Tate_Modern.jpg",
"url": "6year-old-thrown-from-tate-modern",
"category": "London",
"author": "Jo-anne Reay-Harrower",
"content": "A young boy just 6 yrs old from France visiting the Tate Modern in London is currently in a stable but critical condition in hospital suffering from a “ deep bleed to his brain and fractures to his spine, arms and legs after being thrown from a 10th floor balcony at the Tate Modern.\n\nThe young boy was thrown 30 meters by a 17 year old who didn’t even know the victim, the 17 year old has been charged with Attempted murder by the London Police.",
"TweetIDs": [
"1158087492098318336",
"1158115986744184834"
],
"timestamp": "2019-08-09T05:06:00.000Z",
"published": true
},
{
"_id": "5d47fb3c4456f4ee891dfccb",
"title": "Bendigo Woman First Victorian to use new Assisted Dying Act",
"keywords": "Bendigo Woman, Assisted Dying Act, Victoria",
"description": "A 61 yr old mother is the first to Use the new Assisted Dying Act in Victoria",
"image": "https://storage.googleapis.com/radiomedia-images/news/Bendigo-woman-Ms-Kerry-Robertson-VIC-Assisted-Dying-Act.jpg",
"url": "bendigo-woman-first-victorian-to-use-new-assisted-dying-act",
"category": "Australia,Victoria",
"author": "Jo-anne Reay-Harrower",
"content": "A 61 yr old mother is the first to Use the new Assisted Dying Act in Victoria.\n\nMs Kerry Robertson was diagnosed with Breast cancer back in 2010, the cancer gradually spread into her lungs, bone and brain. In March this year Ms Robertson decided to cease treatment for the cancer after it had invaded her liver and the side effects of the treatment could not be managed. After completing the Assisted dying process which took almost a month Ms Robertson was given her medication by the Statewide Pharmacy which end her life she took the medication the day she received it. Ms Robertson had been struggling with severe pain for a long time.\n\nAccording to her daughters who were present at the time the whole procedure was quick. They said that her death was “ Beautiful and Peaceful”.\n\nTo be eligible for the act you must meet Victoria’s strict Criteria such as : be over 18, be an Australian citizen or permanent resident; and reside in Victoria for at least 12 months.\n\nThe person must have decision-making capacity in relation to Voluntary assisted dying and the person must be diagnosed with a disease, illness or medical condition that is incurable; and is advanced, progressive and will cause death; and is expected to cause death within weeks or months, not exceeding 6 months and is causing suffering to the person that cannot be relieved in a manner that the person considers tolerable.\n\nThese are just some of the Act there a lot more that has to be done before a patient is given this medication. You can find out more by reading the Voluntary assisted Dying Act 2017 No. 61 of 2017",
"TweetIDs": [
"1158117726402912256",
"1158186811287412737",
"1157991713152962560"
],
"timestamp": "2019-08-05T09:45:00.201Z",
"published": true
},
{
"_id": "5d47f8ac4456f4ee891dfb83",
"title": "America Shocked By Back To Back Shootings",
"keywords": "America 29 people killed, gun laws, Donald Trump",
"description": "In less than 24 hours America was once again sent reeling in shock to hear of more mass shootings. Between two separate incidents 29 people were left dead and further 56 lay injured. The two shooters were both in their early twenties and both were carrying assault style weapons.",
"image": "https://storage.googleapis.com/radiomedia-images/news/jacob-stone-uF0ZdMnWIZE-unsplash.jpg",
"url": "america-shocked-by-back-to-back-shootings",
"category": "America,Shooting",
"author": "Jo-anne Reay-Harrower",
"content": "In less than 24 hours America was once again sent reeling in shock to hear of more mass shootings.\n\nBetween two separate incidents 29 people were left dead and further 56 lay injured. The two shooters were both in their early twenties and both were carrying assault style weapons.\n\nOn Saturday a 21 yr old opened fire in a Walmart store in El Paso 6 Mexican Nationals were killed. Mexico’s Foreign Minister said that “it’s urgent that we take corresponding action against weapons”.\n\nOn Sunday a 21 yr old opened fire near or at Ned Pepper’s bar killing his 22 yr old sister and eight others, he will never get to face a trail as he was fatally shot by police.\n\nOn Monday President Donald Trump tweeted “ the flags at the white house will be lowered today through Thursday August 8th ….”\n\n “Today, I authorized the lowering of the flags to half mast at all Federal Government buildings in honor of the victims of the tragedies in El Paso, Texas, and Dayton, Ohio.\n\nHowever what can America do about these mass shootings when they federal laws such as the Brady’s Act which tells when you are not allowed to carry a gun but the States have laws that are called open carry laws . Generally the states fall open one of four categories which are , Permissive Open Carry States- allows you to carry a gun without a permit or license, Licensed Open carry states- Allow gun owners to carry firearms openly only after they are issued a permit or license, Anomalous Open Carry States- carrying a gun may be generally lawful under state law, but local governments may pass their own gun laws that may be more restrictive than the state’s laws and Non- Permissive Open Carry States- carrying a gun openly is against the law, or is legal only in Limmited circumstances (e.g. While hunting ) or when legally used for self-defense.\n\nWhen you have a Permissive open carry State that allows any-one of any mental capacity to own a gun surely you are asking for trouble.\n\nThis reporter really does believe God Protect America because it certailnly can’t protect itself with the current gun laws.",
"TweetIDs": [
"1158102730696736768",
"1157849346613948416",
"1158174240606248968"
],
"timestamp": "2019-08-05T09:40:00.201Z",
"published": true
},
{
"_id": "5d47bd49a945f848b4a03d35",
"title": "Channel Ten’s The Project Infighting Backstage.",
"keywords": "The Project TV, Channel Ten, Lisa Wilkinson, Project TV Infighting",
"description": "The Project TV crew Lisa Wilkinson and Peter Helliar buttheads. Members of the crew at The Project TV had to escort Lisa Wilkinson off the set last week.",
"image": "https://storage.googleapis.com/radiomedia-images/news/The_Project_Lisa_Wilkinson_66985279_2320803601491787_800209095162190243_n.jpg",
"url": "the-project-tv-infighting",
"category": "TV,The Project",
"author": "Russell Harrower",
"content": "Channel Ten’s biggest news and current affairs show The Project seems not to be running so smoothly when the camera’s are off.\n\nLast week Peter Helliar took a dig at Lisa Wilkinson during the show s 10’th anniversary. Lisa was escorted out of the set by crew members.\n\nIt’s been said that ‘resentment’ and ‘nasty barbs’ regarding Lisa Wilkinson is fueling the flames and continue to cause issues for the producers and the network.\n\n“There’s been a level of resentment for months about her [Lisa’s] role, because she really isn’t a team player, and I think that sentiment boiled over on the night,” an alleged Channel Ten source told Woman’s Day.\n\n“Lisa is highly sensitive regarding her public profile and, while she tried to keep relationships civil off camera, she is furious that her co-hosts are allowing nasty barbs to continue on air,” they said.\n\nRadioMedia (DRN1) attempted to contact Channel Ten, The Project and Lisa Wilkinson for comment.\rImage: The cast of Channel Ten's The Project. Photo: Instagram/lisa_wilkinson",
"TweetIDs": null,
"timestamp": "2019-08-05T05:23:21.803Z",
"published": true
}
]
}
I need to fetch the data from the URL.
From the flutter docs:
Future<Post> fetchPost() async {
final response =
await http.get('http://api.radiomedia.com.au/api-access/news');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return Main. fromMap(json.decode(response.body)); // MAYBE YOU NEED TO ADAPT HERE A BIT
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
Here are the model classes:
class Main {
List<NewsBean> news;
static Main fromMap(Map<String, dynamic> map) {
if (map == null) return null;
Main mainBean = Main();
mainBean.news = List()..addAll(
(map['news'] as List ?? []).map((o) => NewsBean.fromMap(o))
);
return mainBean;
}
Map toJson() => {
"news": news,
};
}
/// _id : "5d71dbff34eb1563bff1ac87"
/// title : "Billie Eilish All Good Girls Go To Hell (Music Video Review)"
/// keywords : "Billie Eilish, All Good Girls Go To Hell, Music Video, Review"
/// description : "We review Billie Eilish has just released the music video to the much waited fan fair for All Good Girls Go To Hell."
/// image : "https://storage.googleapis.com/radiomedia-images/news/BEAllGoodGirlsGoToHell.jpg"
/// url : "billie_eilish_all_good_girls_go_to_hell_review"
/// category : "Review,Music Video"
/// author : "Russell Harrower"
/// content : "Billie Eilish has just released the music video to the much waited fan fair for All Good Girls Go To Hell.\n\nThe music video which features Billie Eilish opens with an angel falling from the heaven above, then lands in what seems to be tar like substance which Billie slowly drags her body out of.\n\nWhat makes this one of the most interesting music videos I have seen for a long time, is the special effects that had to be used towards the end of the video, where the angel wings seem to turn to bat like wings.\n\nWhile this is only being really picky, you will notice either the quality of the special effects budget might of all been used up in the first half of the video as the bat like wings don't stay centered as she walks away from the camera. But that's just me being REALLY PICKY. The song itself is one of struggle and a song I feel we all can realate to in one way or another. Checkout the video below."
/// youtube : "-PZsSWwc9xA"
/// TweetIDs : []
/// timestamp : "2019-09-06T21:08:20.201Z"
/// published : true
class NewsBean {
String Id;
String title;
String keywords;
String description;
String image;
String url;
String category;
String author;
String content;
String youtube;
List<dynamic> TweetIDs;
String timestamp;
bool published;
static NewsBean fromMap(Map<String, dynamic> map) {
if (map == null) return null;
NewsBean newsBean = NewsBean();
newsBean.Id = map['_id'];
newsBean.title = map['title'];
newsBean.keywords = map['keywords'];
newsBean.description = map['description'];
newsBean.image = map['image'];
newsBean.url = map['url'];
newsBean.category = map['category'];
newsBean.author = map['author'];
newsBean.content = map['content'];
newsBean.youtube = map['youtube'];
newsBean.TweetIDs = map['TweetIDs'];
newsBean.timestamp = map['timestamp'];
newsBean.published = map['published'];
return newsBean;
}
Map toJson() => {
"_id": Id,
"title": title,
"keywords": keywords,
"description": description,
"image": image,
"url": url,
"category": category,
"author": author,
"content": content,
"youtube": youtube,
"TweetIDs": TweetIDs,
"timestamp": timestamp,
"published": published,
};
}
This was generated with flutter to json plugin.
here is serialization
class NewsClass {
List<News> news;
NewsClass({
this.news,
});
factory NewsClass.fromJson(Map<String, dynamic> json) => NewsClass(
news: List<News>.from(json["news"].map((x) => News.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"news": List<dynamic>.from(news.map((x) => x.toJson())),
};
}
class News {
String id;
String title;
String keywords;
String description;
String image;
String url;
String category;
Author author;
String content;
String youtube;
List<String> tweetIDs;
DateTime timestamp;
bool published;
News({
this.id,
this.title,
this.keywords,
this.description,
this.image,
this.url,
this.category,
this.author,
this.content,
this.youtube,
this.tweetIDs,
this.timestamp,
this.published,
});
factory News.fromJson(Map<String, dynamic> json) => News(
id: json["_id"],
title: json["title"],
keywords: json["keywords"],
description: json["description"],
image: json["image"],
url: json["url"],
category: json["category"],
author: authorValues.map[json["author"]],
content: json["content"],
youtube: json["youtube"] == null ? null : json["youtube"],
tweetIDs: json["TweetIDs"] == null ? null : List<String>.from(json["TweetIDs"].map((x) => x)),
timestamp: DateTime.parse(json["timestamp"]),
published: json["published"],
);
Map<String, dynamic> toJson() => {
"_id": id,
"title": title,
"keywords": keywords,
"description": description,
"image": image,
"url": url,
"category": category,
"author": authorValues.reverse[author],
"content": content,
"youtube": youtube == null ? null : youtube,
"TweetIDs": tweetIDs == null ? null : List<dynamic>.from(tweetIDs.map((x) => x)),
"timestamp": timestamp.toIso8601String(),
"published": published,
};
}
enum Author { RUSSELL_HARROWER, JO_ANNE_REAY_HARROWER, PETER_BASSETT_SCARFE }
final authorValues = EnumValues({
"Jo-anne Reay-Harrower": Author.JO_ANNE_REAY_HARROWER,
"Peter Bassett-scarfe": Author.PETER_BASSETT_SCARFE,
"Russell Harrower": Author.RUSSELL_HARROWER
});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
and just map through it, i'd also recommend that you use code generator like this : quick type
Other answers are correct , in addition you can create those methods by using library..
in flutter documentation : https://flutter.dev/docs/development/data-and-backend/json
they used https://pub.dev/packages/json_serializable so its should be simpler like that :
import 'package:json_annotation/json_annotation.dart';
part 'news_bean.g.dart';
#JsonSerializable()
class NewsBean {
//NewsBean..constructor
//props
factory NewsBean.fromJson(Map<String, dynamic> json) =>
_$NewsBeanFromJson(json);
Map<String, dynamic> toJson() => _$NewsBeanToJson(this);
}
I am trying to extract data from a JSON file. Here is my code.
import json
json_file = open('test.json')
data = json.load(json_file)
json_file.close()
At this point I can print the file using print data and it appears that the file has been read in properly.
Now I would like to grab a value from a key:value pair that is in a dictionary nested within a list nested within a dictionary (Phew!). My initial strategy was to create a dictionary and plop the dictionary nested within the list in it and then extract the key:value pairs I need.
dict = {}
dict = json_file.get('dataObjects', None)
dict[0]
When I try to look at the contents of dict, I see that there is only one element. The entire dictionary appears to have been read as a list. I've tried a couple of different approaches, but I still wind up with a dictionary read as a list. I would love to grab the nested dictionary and use another .get to grab the values I need. Here is a sample of the JSON I am working with. Specifically, I am trying to pull out the identifier and description values from the dataObjects section.
{
"identifier": 213726,
"scientificName": "Carcharodon carcharias (Linnaeus, 1758)",
"richness_score": 89.6095,
"synonyms": [
],
"taxonConcepts": [
{
"identifier": 20728481,
"scientificName": "Carcharodon carcharias (Linnaeus, 1758)",
"nameAccordingTo": "WORMS Species Information (Marine Species)",
"canonicalForm": "Carcharodon carcharias",
"sourceIdentfier": "105838"
},
{
"identifier": 24922984,
"scientificName": "Carcharodon carcharias",
"nameAccordingTo": "IUCN Red List (Species Assessed for Global Conservation)",
"canonicalForm": "Carcharodon carcharias",
"sourceIdentfier": "IUCN-3855"
},
],
"dataObjects": [
{
"identifier": "5e1882d822ec530069d6d29e28944369",
"dataObjectVersionID": 5671572,
"dataType": "http://purl.org/dc/dcmitype/Text",
"dataSubtype": "",
"vettedStatus": "Trusted",
"dataRating": 3.0,
"subject": "http://rs.tdwg.org/ontology/voc/SPMInfoItems#TaxonBiology",
"mimeType": "text/html",
"title": "Biology",
"language": "en",
"license": "http://creativecommons.org/licenses/by-nc-sa/3.0/",
"rights": "Copyright Wildscreen 2003-2008",
"rightsHolder": "Wildscreen",
"audience": [
"General public"
],
"source": "http://www.arkive.org/great-white-shark/carcharodon-carcharias/",
"description": "Despite its worldwide notoriety, very little is known about the natural ecology and behaviour of this predator. These sharks are usually solitary or occur in pairs, although it is apparently a social animal that can also be found in small aggregations of 10 or more, particularly around a carcass (3) (6). Females are ovoviviparous; the pups hatch from eggs retained within their mother's body, and she then gives birth to live young (10). Great white sharks are particularly slow-growing, late maturing and long-lived, with a small litter size and low reproductive capacity (8). Females do not reproduce until they reach about 4.5 to 5 metres in length, and litter sizes range from two to ten pups (8). The length of gestation is not known but estimated at between 12 and 18 months, and it is likely that these sharks only reproduce every two or three years (8) (11). After birth, there is no maternal care, and despite their large size, survival of young is thought to be low (8). Great whites are at the top of the marine food chain, and these sharks are skilled predators. They feed predominately on fish but will also consume turtles, molluscs, and crustaceans, and are active hunters of small cetaceans such as dolphins and porpoises, and of other marine mammals such as seals and sea lions (12). Using their acute senses of smell, sound location and electroreception, weak and injured prey can be detected from a great distance (7). Efficient swimmers, sharks have a quick turn of speed and will attack rapidly before backing off whilst the prey becomes weakened; they are sometimes seen leaping clear of the water (6). Great whites, unlike most other fish, are able to maintain their body temperature higher than that of the surrounding water using a heat exchange system in their blood vessels (11).",
"agents": [
{
"full_name": "ARKive",
"homepage": "http://www.arkive.org/",
"role": "provider"
}
],
}
]
}
The source you provide cannot be read by json, there are two comma's in there that you have to delete (the one on the fourth line from the bottom, and the one two lines above dataObjects.
Only after that does the json module parse without error:
import json
json_file = open('test.json')
data = json.load(json_file)
do = data['dataObjects'][0]
print do['identifier']
print do['description']
json_file.close()