how can i make post method in flutter? - json

How can i make post method in flutter for json like this
{
"app_id": "3djdjkdjde",
"include_external_user_ids": ["88"],
"contents": {"en": "your order is created"}
}
as you see its json inside json my problem in contents it's has a json as its value
i made this model with post method but i don't know how can i parse content you can see i make it's value null for now
it's okay if contents with static message no need for dynamic value in this time
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Notifications notificationsFromJson(String str) => Notifications.fromJson(json.decode(str));
String notificationsToJson(Notifications data) => json.encode(data.toJson());
class Notifications {
String appId;
List<String> includeExternalUserIds;
Contents contents;
Notifications({
this.appId,
this.includeExternalUserIds,
this.contents,
});
factory Notifications.fromJson(Map<String, dynamic> json) => new Notifications(
appId: json["app_id"],
includeExternalUserIds: new List<String>.from(json["include_external_user_ids"].map((x) => x)),
contents: Contents.fromJson(json["contents"]),
);
Map<String, dynamic> toJson() => {
"app_id": appId,
"include_external_user_ids": new List<dynamic>.from(includeExternalUserIds.map((x) => x)),
"contents": contents.toJson(),
};
static Future<bool> postNotification(serviceUri, notificationData) async {
var client = new http.Client();
bool result = false;
try {
final Map<String, String> _notificationData = {
'app_id': notificationData['app_id'].toString(),
'include_external_user_ids': orderData['include_external_user_ids'].toString(),
"contents": null,
};
await client.post(serviceUri,
body: json.encode(_notificationData),
headers: { 'Authorization' : 'Bearer ' + notificationData['Token'], "Content-Type": "application/json"}
)
.then((http.Response response) {
var responseModel = json.decode(response.body);
if(responseModel != null && responseModel['status'] == true) {
result = true;
} else {
result = false;
}
});
}
catch(e) {
result = false;
}
finally {
client.close();
}
return result;
}
}
class Contents {
String en;
Contents({
this.en,
});
factory Contents.fromJson(Map<String, dynamic> json) => new Contents(
en: json["en"],
);
Map<String, dynamic> toJson() => {
"en": en,
};
}
thanks

Future<Map<String, dynamic>> postRequest(String url, Map jsonMap) async{
print('$url , $jsonMap');
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
httpClient.close();
Map<String, dynamic>map = json.decode(reply);
return map;
}
Add this http: ^0.12.0+1 in your pubspec.yaml file

Related

Parsing Nested JSON leads to fromJson methods having a "The class 'Data' doesn't have an unnamed constructor." error

So I am trying to parse a Nested JSON from a GET request from VirusTotal but when I create the methods to parse the JSON for what I am looking for it is giving me an error on the factory methods immediately following the =>. I used the tool https://app.quicktype.io/ to get this method but it still does not seem to work. The JSON I am looking to parse looks like this and the code is below that.
{
"data": {
"attributes": {
"last_analysis_stats": {
"harmless": 81,
"malicious": 2,
"suspicious": 0
}
}
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sms/sms.dart';
import 'package:http/http.dart' as http;
Future<void> main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key:key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: "Gone Smishin'",
home: GoneSmishin(),
);
}
}
class GoneSmishin extends StatefulWidget {
const GoneSmishin({Key? key}) : super(key: key);
State<GoneSmishin> createState() {
return _GoneSmishinState();
}
}
class Data {
late Attributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data( // this is where the error appears in every method
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"attributes": attributes.toJson(),
};
}
class Attributes {
late LastAnalysisStats lastAnalysisStats;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
lastAnalysisStats: LastAnalysisStats.fromJson(json["last_analysis_stats"]),
);
Map<String, dynamic> toJson() => {
"last_analysis_stats": lastAnalysisStats.toJson(),
};
}
class LastAnalysisStats {
static late int harmless;
static late int malicious;
static late int suspicious;
factory LastAnalysisStats.fromJson(Map<String, dynamic> json) => LastAnalysisStats(
harmless: json["harmless"],
malicious: json["malicious"],
suspicious: json["suspicious"],
);
Map<String, dynamic> toJson() => {
//"harmless": harmless,
"malicious": malicious,
"suspicious": suspicious,
};
}
class _GoneSmishinState extends State<GoneSmishin> {
late Data data;
String message = "";
String word = "";
bool isOn = false;
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
var queryStatus = '';
var urlStatus = '';
var attributes = '';
String urlHaus = "URLHaus";
String virusTotal = "VirusTotal";
String list = "Whitelist";
urlHausParseBox() async {
String url = myController.text;
var urlEncoded = base64.encode(utf8.encode(myController.text));
var urlNoPadding = urlEncoded.replaceAll(new RegExp(r'='), '');
// await VirusTotal().getUrlAnalysisReport(urlNoPadding);
final response2 = await http.get(
Uri.parse("https://www.virustotal.com/api/v3/urls/$urlNoPadding"),
headers: <String, String>{
'Accept': 'application/json',
'x-apikey': '111111111111111111111'
},
);
print(urlEncoded);
print(response2.body);
if (response2.statusCode == 200) {
setState(() {
final decoded = json.decode(response2.body);
data = decoded['data'];
});
}
if (queryStatus == "ok" && urlStatus == "online") {
print("found");
setState(() {
urlHaus = 'Found in URLHause Database - Probably Smishing';
});
} else if (queryStatus == "ok" && urlStatus == "offline") {
print("found offline");
setState(() {
urlHaus = 'Found in URLHaus, not online';
});
} else {
print("not found");
setState(() {
urlHaus = 'Found Nothing';
});
}
if (((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious)) >= 2) {
setState(() {
virusTotal = 'Found in VirusTotal - Possibly Malicious';
});
} else
if (((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious)) <= 1) {
setState(() {
virusTotal = 'Found in VirusTotal - Probably not Malicious';
print((LastAnalysisStats.suspicious) + (LastAnalysisStats.malicious));
});
} else {
setState(() {
virusTotal = 'Not found in VirusTotal';
});
}
Can you try to use the json model like this?
import 'dart:convert';
Model modelFromJson(String str) => Model.fromJson(json.decode(str));
String modelToJson(Model data) => json.encode(data.toJson());
class Model {
Model({
this.data,
});
Data data;
factory Model.fromJson(Map<String, dynamic> json) => Model(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
this.attributes,
});
Attributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data(
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"attributes": attributes.toJson(),
};
}
class Attributes {
Attributes({
this.lastAnalysisStats,
});
LastAnalysisStats lastAnalysisStats;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
lastAnalysisStats: LastAnalysisStats.fromJson(json["last_analysis_stats"]),
);
Map<String, dynamic> toJson() => {
"last_analysis_stats": lastAnalysisStats.toJson(),
};
}
class LastAnalysisStats {
LastAnalysisStats({
this.harmless,
this.malicious,
this.suspicious,
});
int harmless;
int malicious;
int suspicious;
factory LastAnalysisStats.fromJson(Map<String, dynamic> json) => LastAnalysisStats(
harmless: json["harmless"],
malicious: json["malicious"],
suspicious: json["suspicious"],
);
Map<String, dynamic> toJson() => {
"harmless": harmless,
"malicious": malicious,
"suspicious": suspicious,
};
}

Error when trying to decode json with Iterable in Flutter

I'm trying to get this simple json response in Flutter, but getting this error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable< dynamic >'. I found some people with the same error but the solutions it's not clearly to me. The error occurs on jsonDecode(response.body);, in debug mode, when reachs the response.body, the exception occurs.
{
"#bom": 4,
"#jantar": 3,
"#paris": 2,
}
My model:
import 'dart:convert';
List<Hashtags> hashtagsFromJson(String str) => List<Hashtags>.from(json.decode(str).map((x) => Hashtags.fromJson(x)));
String hashtagsToJson(List<Hashtags> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Hashtags {
Hashtags({
this.hashtag,
});
int? hashtag;
factory Hashtags.fromJson(Map<String, dynamic> json) => Hashtags(
hashtag: json["hashtag"],
);
Map<String, dynamic> toJson() => {
"hashtag": hashtag,
};
}
and my get method:
Future<List<Hashtags>> getHashtagTop() async {
var url = Uri.parse(baseUrl + 'hashtagTop');
final Map<String, String> dataBody = new Map<String, String>();
dataBody['uid'] = appController.currentUser.value.id.toString();
try {
http.Response response = await http.post(
url,
headers: headers,
body: jsonEncode(dataBody),
);
if (response.statusCode == 200 || response.statusCode == 201) {
Iterable jsonResponse = jsonDecode(response.body);
List<Hashtags> listHashtagTop =
jsonResponse.map((model) => Hashtags.fromJson(model)).toList();
return listHashtagTop;
} else {
return [];
}
} catch (e) {
print("ERRO_______________" + e.toString());
return [];
}
}
So what is missing here?
Change your decoding function to this
final results = [jsonDecode(response.body)];
List<Hashtags> listHashtagTop =
results.map((model) => Hashtags.fromJson(model)).toList();
Try this and let you know

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'SubJsonModel' - flutter

Am trying to get a data from a json url but i get the error
Unhandled Exception: type 'List' is not a subtype of type 'SubJsonModel'
main.dart
final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() async {
var res = await http.get(url, headers: {"Accept":"application/json"});
if(res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for(var data in jsonDecode) {
myModel.add(JsonModel(data['cat_id'], data['category'], data['cat_subcategory']));
setState(() {});
}
print(myModel[1].subCat.name);
}else {
print("Something went wrong!");
}
}
model.dart
class JsonModel {
final String id;
final String category;
SubJsonModel subCat;
JsonModel(this.id, this.category, this.subCat);
}
class SubJsonModel {
final String name;
final String image;
SubJsonModel(this.name, this.image);
}
please how do i solve this
So here what I do first create a model class with the help of this online tool. And then changed code like first save subcategory in one list and then passed it to the main list and then print
Here is my loadData() method
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List myModel = [];
loadData() async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
List<CatSubcategory> subCate = []; // Set a emoty list of CatSubcategory
data['cat_subcategory'].map((x) { // Here parsed the cat_subcategory data and simply add it into list
return subCate.add(
CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
}).toList(); // and this done for we get map data so convert this data toList();
myModel.add(JsonModel(
category: data['category'],
catId: data['cat_id'],
catIcon: data['cat_icon'],
catSubcategory: subCate));
setState(() {});
}
print(myModel[0].catSubcategory[0].subName);
} else {
print("Something went wrong!");
}
}
here is my model class
class JsonModel {
JsonModel({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(
json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon,
"cat_subcategory":
List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
You can use https://app.quicktype.io/ to create the model.dart from a json.
To parse this JSON data, do
final pieSingleChartInfo = pieSingleChartInfoFromJson(jsonString);
import 'dart:convert';
List<PieSingleChartInfo> pieSingleChartInfoFromJson(String str) => List<PieSingleChartInfo>.from(json.decode(str).map((x) => PieSingleChartInfo.fromJson(x)));
String pieSingleChartInfoToJson(List<PieSingleChartInfo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class PieSingleChartInfo {
PieSingleChartInfo({
this.category,
this.catId,
this.catIcon,
this.catSubcategory,
});
String category;
String catId;
String catIcon;
List<CatSubcategory> catSubcategory;
factory PieSingleChartInfo.fromJson(Map<String, dynamic> json) => PieSingleChartInfo(
category: json["category"],
catId: json["cat_id"],
catIcon: json["cat_icon"] == null ? null : json["cat_icon"],
catSubcategory: List<CatSubcategory>.from(json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"cat_id": catId,
"cat_icon": catIcon == null ? null : catIcon,
"cat_subcategory": List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
};
}
class CatSubcategory {
CatSubcategory({
this.subName,
this.subImage,
});
String subName;
String subImage;
factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
subName: json["sub_name"],
subImage: json["sub_image"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"sub_image": subImage,
};
}
I noted a few issues and corrected them based on the information you provided.
Read the comments. Add a sample response body to the question.
final String url =
'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];
#override
void initState() {
// TODO: implement initState
super.initState();
loadData();
}
loadData() async {
var res = await http.get(url, headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
String resBody = res.body;
var jsonDecode = json.decode(resBody);
for (var data in jsonDecode) {
// first create SubJsonModel object
var subCat = SubJsonModel(
data['cat_subcategory']['name'], data['cat_subcategory']['image']);
//use subCat to create JsonModel
myModel.add(JsonModel(data['cat_id'], data['category'], subCat));
setState(() {});
}
print(myModel[1].subCat.name);
} else {
print("Something went wrong!");
}
}

problem converting json response to object in Flutter

first all sorry about my "engrish"...
I'm trying to consume an own API method with http package in Flutter.
I'm able to get a response from API but I'm having trouble trying to map the response (json) to my custom object called APILoginResponse.
I'm calling the API method like this:
APILoginResponse apiLogin = await api.apiLogin();
but I'm getting a runtime error "dynamic is not subtype of AccessToken".
Here is my API login method:
Future<APILoginResponse> apiLogin() async {
final http.Response response = await http.post(
api_end_point + '/api/Auth/login',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{'userName': api_user, 'password': api_password}),
);
if (response.statusCode == 200) {
return APILoginResponse.fromJson(json.decode(response.body));
} else {
throw Exception('Error en login de la API');
}
}
...and here is my APILoginResponse object:
class APILoginResponse {
final AccessToken accessToken;
final String refreshToken;
APILoginResponse({this.accessToken, this.refreshToken});
factory APILoginResponse.fromJson(Map<String, dynamic> json) {
return APILoginResponse(
accessToken: json['accessToken'],
refreshToken: json['refreshToken'],
);
}
}
class AccessToken {
String token;
int expiresIn;
}
error is in the line:
accessToken: json['accessToken']
inside APILoginResponse class.
Here is my json response:
{
"accessToken": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiIiLCJzdWIiOiJib3N0b25jcmVkX2NsaWVudGVzIiwianRpIjoiZjBkMzY0ZDMtMmRkNS00NzkzLWE5ZTktMzY1YzJmODNiYmI3IiwiaWF0IjoxNTk0MTMxODAwLCJyb2wiOiJhcGlfYWNjZXNzIiwiaWQiOiIyMzg3YTMzZi1hYzE5LTRhMzYtODcyZC04MTE3MzExZDFjY2IiLCJuYmYiOjE1OTQxMzE3OTksImV4cCI6MTU5NDEzMjM5OSwiaXNzIjoid2ViQXBpIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMTcvLyJ9.PqCPkVct4e4duWFEr63fALZ0h_0x25vsV_GBx336Apw",
"expiresIn": 600
},
"refreshToken": "W6wyiw9xYuC2UaJmyCOYujKIZTs0jAscnfcWTrEyVIk="
}
Any help with this will be appreciated. Thanks!
If you are sure that the returning value is an AccessToken you can try this:
factory APILoginResponse.fromJson(Map<String, dynamic> json) {
return APILoginResponse(
accessToken: (json['accessToken'] as Map<String,dynamic>) as AccessToken ?? null,
refreshToken: json['refreshToken'],
);
}
Change your AccessToken class to this:
class AccessToken {
final Map<String,dynamic> tokenData;
AccessToken(tokenData)
}
well I think #P4yam answer was right but I was getting the same error over and over, so I changed my APILoginResponse class as follow:
class APILoginResponse {
AccessToken accessToken;
String refreshToken;
APILoginResponse({this.accessToken, this.refreshToken});
APILoginResponse.fromJson(Map<String, dynamic> json) {
accessToken = json['accessToken'] != null
? new AccessToken.fromJson(json['accessToken'])
: null;
refreshToken = json['refreshToken'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.accessToken != null) {
data['accessToken'] = this.accessToken.toJson();
}
data['refreshToken'] = this.refreshToken;
return data;
}
}
class AccessToken {
String token;
int expiresIn;
AccessToken({this.token, this.expiresIn});
AccessToken.fromJson(Map<String, dynamic> json) {
token = json['token'];
expiresIn = json['expiresIn'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['token'] = this.token;
data['expiresIn'] = this.expiresIn;
return data;
}
}
and everything works fine now! thanks!

How to pass nested Json into my http API in Dart

I need to pass json data into my http APIs. I am not able to find the right way to do this yet. Here's my code snippet:
For all interactions to/from API, I have created an Dbhelper class.
Here's my Dbhelper class
class Dbhelper {
String fbody; // json parameter
Map result; // Response json for the api called
Dbhelper({this.fbody});
Future<void> executeData() async {
try {
//Make post request
Response response = await post('http://<my domain>/api/GetInfo',headers: {"content-type":"application/json"},body: $fbody);
var deviceinfo = jsonDecode(response.body);
print('In dbhelper $deviceinfo');
result = deviceinfo;
} catch(e) {
print('Something occured $e');
result = null;
}
}
}
This is what i am trying to do. I have login class which takes input from UI - UserName and password and need to pass this into Dbhelper object.
the intended json to be passed in my API is :
{
"strjson":{ "cUserName":"sandy" , "cPassword":"12345" },
"strSPName":"App_Userlogin"
}
toMap(String u, String p ){
return {
"strSPName":"App_userregister",
"strjson":{
"cUserName":u,
"cPassword":p
}
};
}
void _checkLogin(String u , String p) async {
try {
Map inputs = toMap(u,p);
print(inputs);
Dbhelper db = Dbhelper(fbody: inputs);
await db.executeData();
User user = User.fromJson(db.result);
if (user.uid >0)
Navigator.of(context).pushReplacementNamed('home');
else
print("User not found");
}catch(e){
print(e.toString());
User user = User(uid:0,username:'',userbalance: 0);
}
}
Please help me what I am missing in this
While passing body to http.post request . Try passing body inside single quotes.
Response response = await post('http://<my domain>/api/GetInfo',headers: {"content-type":"application/json"},body: '$fbody');
If this doesn't work, you can try encoding your body in json format using jsonEncode as shown
body: jsonEncode(<String, String> {'uname':'SomeName',})
Hope this works!
Json that I have posted in body..
{
"user": {
"UserName": "username",
"password": "password",
"Name": "name",
"Email": "email"
}
}
Your Post Api call be like:
Future<User> postUser(String username, String password, String name, String
email) async {
Paste your api url here
String url = '';
final response = await http.post(apiUrl, headers: {
// Enter your headers parameter if needed
// E.g:
'Authorization' : 'xyz',
'Content-Type' : 'application/json'
},
body: jsonEncode(<String, String>{
'UserName' : username,
'password' : password,
'Name' : name,
'Email' : email
}));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to post user.');
}
}
Your model be like:
class User {
User? user;
User({this.user});
User.fromJson(Map<String, dynamic> json) {
user = json['user'] != null ? new User.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user != null) {
data['user'] = this.user!.toJson();
}
return data;
}
}
class User {
String? userName;
String? password;
String? name;
String? email;
User({this.userName, this.password, this.name, this.email});
User.fromJson(Map<String, dynamic> json) {
userName = json['UserName'];
password = json['password'];
name = json['Name'];
email = json['Email'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['UserName'] = this.userName;
data['password'] = this.password;
data['Name'] = this.name;
data['Email'] = this.email;
return data;
}
}