Display the complete json data from API response in flutter - json

I'm getting the json data from the API call but its not displaying the complete data.There are a lot of properties to work with and creating the model would be difficult as it's my first time working on any API.So i wanted to use app.quicktype.io to parse the json data directly into dart code for which i need to get the complete json data.Right now only little bit of the json data is being displayed in the console.
CODE:
Future<void> getContacts() async {
var client = http.Client();
String contacts_url =
'https://mylinkexample.com';
String basicAuth =
'Basic mykeyexampele';
var response = await client.get(contacts_url,
headers: <String, String>{'authorization': basicAuth});
var jsonString = jsonDecode(response.body);
print(response.statusCode);
print(jsonString);
}

Use this :
import 'dart:developer' as developer;
test() {
developer.log(response.body);
}

Related

I'm trying to make a simple app in flutter that fetches data from an API. However when I try running the code I get the following error

"Dart Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' "
It says that the error is in the following line:
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
For context, the entire code is this:
class _HomePageState extends State<HomePage> {
final List<Object> _objects = [];
Future<List<Object>> fetchData() async{
const String urlString = 'https://api.publicapis.org/entries';
final Uri url = Uri.parse(urlString);
var response = await http.get(url);
final List<Object> objects = [];
if(response.statusCode == 200){
var jsonObjects = json.decode(response.body);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
}
return objects;
}
Any help would be greatly appreciated. Thanks.
Main problem is that response.body is not a list of elements, and you are assuming it is. Instead of that, it's a "key" : "value" type of json object, which cannot be iterated.
The for (var e in collection) syntax is made to be used with an Iterable collection, and _InternalLinkedHashMap (and maps in general) are not iterables.
The solution is to parse the response properly. Check this link if you want to follow best practices for flutter development json parsing.
Your api response's body is a Map:
{"count":1425,
"entries":[
{"API":"AdoptAPet","Description":"Resource to help get pets adopted","Auth":"apiKey","HTTPS":true,"Cors":"yes","Link":"https://www.adoptapet.com/public/apis/pet_list.html","Category":"Animals"},
{"API":"Axolotl","Description":"Collection of axolotl pictures and facts","Auth":"","HTTPS":true,"Cors":"no","Link":"https://theaxolotlapi.netlify.app/","Category":"Animals"},
...
]
}
what you are looking for is a list, Try this:
var jsonObjects = json.decode(response.body["entries"]);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}

How to Read JSON file in Dart console app?

This is a full-console app in dart. Its not flutter.
I need to import data from a local json file and send it as response. I need to read the data as array of Map in dart. The data is in following format.
{
"users":[
{
"id":1,
"user":"user1",
"password":"p455w0rd"
},
{
"id":2,
"user":"user2",
"pass":"p455w0rd"
}
]
}
Every where I see the Flutter example which imports flutter/services as rootBundle to read into the JSON file. I do not find a way to implement this in pure dart.
Use dart:io and dart:convert.
Simple example below. Remember to add exception handling if the file does not exist or has wrong format.
import 'dart:convert';
import 'dart:io';
Future<List<Map>> readJsonFile(String filePath) async {
var input = await File(filePath).readAsString();
var map = jsonDecode(input);
return map['users'];
}
Below is the sample code which you can use to synchronously read a text/json file as a string, displays its content and creates corresponding objects. This will work without using any flutter classes.
For reading JSON/txt file,user 'dart:io' package.
Once the file has been read as a string, use JsonDecoder class to convert the json into corresponding data model objects
import 'dart:io';
import 'dart:convert';
const String FILEPATH = "C:\\test\\dartlang\\users.json";
const JsonDecoder decoder = JsonDecoder();
class USER {
int? id;
String? user;
String? password;
//{ } - implies named arguments
USER({this.id, this.user, this.password});
#override
String toString() {
return "{id:$id,user:$user,password:$password}";
}
}
void main() {
List<USER>? eMP;
//synchronously read file contents
var jsonString = File(FILEPATH).readAsStringSync();
//print(jsonString);
//pass the read string to JsonDecoder class to convert into corresponding Objects
final Map<String, dynamic> jsonmap = decoder.convert(jsonString);
//DataModel - key = "users", value = "ARRAY of Objects"
var value = jsonmap["users"];
if (value != null) {
eMP = <USER>[];
//Each item in value is of type::: _InternalLinkedHashMap<String, dynamic>
value.forEach((item) => eMP?.add(new USER(id:item["id"],user:item["user"],password:item["password"] )));
}
eMP?.forEach((element) => print(element));
}
Save the following json file in your filepath.
{
"users":[{"id":1,"user":"user1", "password":"p455w0rd"},
{"id":2,"user":"user2","password":"p455w0rd"}
]
}
First import dart:convert.
You can parse data from a JSON file as follows:
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
final users = data['users'];
// ...
}

How to parse the JSON response from URL in flutter

I am new to flutter and want to parse the data from a URL that is in json format. The url that I am using is json link .
I want to get the "verse" and "chapter" fields from the json array. I have succeeded in getting the response body in snackbar but not able to get single values. I want to get the "verse" and "chapter" and show then in text box. I am using Dart.
Here is the method that I am using:
_makeGetRequest() async {
// make request
var url = Uri.parse("http://quotes.rest/bible/vod.json");
Response response = await http.get(url);
// sample info available in response
int statusCode = response.statusCode;
Map<String, String> headers = response.headers;
String contentType = headers['content-type'];
String json = response.body;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(json)));
}
#override
void initState() {
super.initState();
streamingController.config(url: "http://stream.zeno.fm/qa8p6uz2tk8uv");
streamingController.play();
_makeGetRequest();
}
Please help me in getting the proper field values and set them in text box as I am trying to solve it from past two days and have tried all solutions from internet but getting exceptions.
use jsonDecode
Map<String,dynamic> data = jsonDecode(response.body);
String verse = data["contents"]["verse"];
dynamic chapter= data["contents"]["chapter"];
however I recommend modeling your data

Unable to post a http request with json body because jsonEncode method from 'dart:convert' package adding escape character

I am trying to make an http post request using http/http.dart package with a JSON body. For that I am trying to convert a Map to JSON using jsonEncode (dart:convert package) but unable to do so as jsonEncode is adding escape character during conversion which makes the JSON string an invalid JSON for post.
Future postData(Map data) async {
Map<String, String> headers = {"Content-type": "application/json"};
var body = jsonEncode(data);
http.Response response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
When I am debugging above code the value for body is coming as below:
body = {\"first_name\":\"Manish\",\"last_name\":\"Kumar\",\"phone_numebr\":\"9123456789\",\"seal\":\"manne\"}
So here I can see an extra escape character being added to the json string which is making it hard to make an http post request with json body.
I tried making http post request by directly placing this string and it worked fine. Code below:
http.Response response = await http.post(url, headers: headers, body: '{"first_name":"Manish","last_name":"Kumar","phone_numebr":"9123456789","seal":"manne"}');
Can someone please help me converting a Map to json without escape characters?
Finally I got the answer.
I created a dataTest variable as below:
final dataTest = {
'first_name': firstName,
'last_name': lastName,
'seal': seal,
'phone_number': phoneNumber
};
Here firstName, lastName, seal and phoneNumber are of string type.
Now call,
postData(dataTest);
Future postData(dynamic data) async {
Map<String, String> headers = {"Content-type": "application/json"};
http.Response response = await http
.post(url, headers: headers, body: json.encode(data));
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
So here the key is to call json.encode method on dynamic type and then pass it to the body parameter of http.post.

WP8 Sending JSON to Server

I am trying to POST some JSON data to my Server. I am using simple code which I have attained from: Http Post for Windows Phone 8
Code:
string url = "myserver.com/path/to/my/post";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "{ \"my\" : \"json\" }";
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
I am getting an error though on await and Task:
Anyone see the obvious error?
Fixed it by changing method signature to:
public async Task ReportSighting(Sighting sighting)