How to encode Map into Json in Dart? - json

I am trying to convert Map<DateTime,List> into json with following code:
String ecoded = json.encode({
DateTime.now(): ["Sample data", 3,true,"Example", 2],
});
But compiler give following error:
E/flutter (11773): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled
Exception: Converting object to an encodable object failed: _LinkedHashMap len:1
E/flutter (11773): #0 _JsonStringifier.writeObject
(dart:convert/json.dart:688:7)
E/flutter (11773): #1 _JsonStringStringifier.printOn
(dart:convert/json.dart:877:17)
E/flutter (11773): #2 _JsonStringStringifier.stringify
(dart:convert/json.dart:862:5)
E/flutter (11773): #3 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter (11773): #4 JsonCodec.encode (dart:convert/json.dart:172:45)
I converted many times Map into json but in all cases Map was something like that:
Map<String,dynamic>
This error is occurring because there is List
If anyone know how to convert Map<DateTime,List> into json then Answer this question.
Thanks

Json only supports Strings as keys. So if you want to use DateTimes as keys you have to manually convert it first:
String ecoded = json.encode({
DateTime.now().toString(): ["Sample data", 3,true,"Example", 2],
});
or
Map<String, dynamic> result = datetimeMap.map((k, v) => MapEntry('$k', v))

In dart programming, json.encode(DateTime.Now()) which is not possible. You need to convert by using Iso8601String() or toString()
String ecoded = json.encode({
DateTime.now().toIso8610String(): ["Sample data", 3,true,"Example", 2],
});

Related

API json no values, The method '[]' was called on null

I'm using World Air Quality API. I need 3 values "AQI", "PM10" and "PM25". Some cities dosen't have value PM10 and my app is freezing on request with error:
E/flutter ( 1339): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 1339): Receiver: null
E/flutter ( 1339): Tried calling: []("v")
How I can add if statement for checking if this value [pm10][v] exist in json?
My code looks like this:
AirQuality(Map<String, dynamic> jsonBody){
aqi = int.tryParse(jsonBody['data']['aqi'].toString()) ??-1;
pm25 = int.tryParse(jsonBody['data']['iaqi']['pm25']['v'].toString()) ??-1;
pm10 = int.tryParse(jsonBody['data']['iaqi']['pm10']['v'].toString()) ??-1;
}

Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)

I was following this flutter beginner tutorial from net ninja here .But my timezone UTC +5:30 in Sri Lanka so i tried to add the half an hour but it keep getting this error that I cant fix. Please help me if you can!!.
Full Traceback error:
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 797ms.
E/flutter (31824): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter (31824): 5:3
E/flutter (31824): ^
E/flutter (31824):
E/flutter (31824): #0 int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
E/flutter (31824): #1 int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
E/flutter (31824): #2 int._parse (dart:core-patch/integers_patch.dart:100:12)
E/flutter (31824): #3 int.parse (dart:core-patch/integers_patch.dart:63:12)
E/flutter (31824): #4 WorldTime.getTime (package:world_time_app/services/world_time.dart:24:39)
E/flutter (31824): <asynchronous suspension>
E/flutter (31824): #5 _LoadingState.SetupWorldTime (package:world_time_app/pages/loading.dart:14:3)
E/flutter (31824): <asynchronous suspension>
E/flutter (31824):
Code :
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'dart:convert';
class WorldTime{
String location;
String time;
String flag;
String url;
WorldTime({this.location, this.flag, this.url});
Future<void> getTime() async{
Response response = await get('https://www.worldtimeapi.org/api/timezone/$url');
Map data = jsonDecode(response.body.toString());
//print(data);
String datetime = data['datetime'];
String offset = data['utc_offset'].substring(2,5);
//print(dataTime);
//print(offset);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset)));
time = now.toString();
print(time);
}
}
In my case I was passing subroutes inside authority parameter, like this:
var response =
await http.get(Uri.https('https://favqs.com/api/quotes/', '4'), headers: {
'Content-Type': 'application/json',
'Authorization': "Token token='xxxxxxxxxxxxxxxx'",
});
but after removing https and moving /api/quotes/ in the second parameter, the issue got solved.
var response =
await http.get(Uri.https('favqs.com', '/api/quotes/4'), headers: {
'Content-Type': 'application/json',
'Authorization': "Token token='xxxxxxxxxxxxxxxx'",
});
You are trying to parse 5:3 as int, which causes the error.
The issue is in the substring that is returning an invalid number (5:3).
First you should do data['utc_offset'].substring(1,3) to get only the hour
And data['utc_offset'].substring(4,6) to get only the minutes.
After that, you can manipulate as you wish, like:
String offsetHours = data['utc_offset'].substring(1, 3);
String offsetMinutes = data['utc_offset'].substring(4, 6);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(
hours: int.parse(offsetHours),
minutes: int.parse(offsetMinutes)),
);

Mapping a class to json while calling an Api showing error in flutter

Map<String, dynamic> toJson() => {
"username": username,
"Event_date_time": eventDateTime,
"Event_name": eventName,
"Event_Address": eventAddress,
"Utensils": utensils,
"Hot_serve": hotServe,
"Carting": carting,
"Beverage ": List<dynamic>.from(Beverage.map((x) => x.toJson())),
};
class Beverage {
String beveragesitem;
String beveragesCount;
Beverage({
this.beveragesitem,
this.beveragesCount,
});
factory Beverage.fromJson(Map<String, dynamic> json) => Beverage(
beveragesitem: json["Beveragesitem"],
beveragesCount: json["Beverages_count"],
);
Map<String, dynamic> toJson() => {
"Beveragesitem": beveragesitem,
"Beverages_count": beveragesCount,
};
}
Error showing like below
Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.
E/flutter ( 6308): Receiver: null
E/flutter ( 6308): Tried calling: length
E/flutter ( 6308): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 6308): #1 _Uri._uriEncode (dart:core-patch/uri_patch.dart:44:23)
E/flutter ( 6308): #2 Uri.encodeQueryComponent (dart:core/uri.dart:1103:17)
E/flutter ( 6308): #3 mapToQuery. (package:http/src/utils.dart:19:13)
E/flutter ( 6308): #4 CastMap.forEach. (dart:_internal/cast.dart:286:8)
E/flutter ( 6308): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
Can anyone help correcting this issue?
Where are you calling toJson()maybe there is the problem?
I have found the issue, may be this will help someone, I was trying to call an Api here with random values for testing purpose. some values were empty while I was testing, when the model class doesnot find value in the structure throwing error as 'length' was called on null, i.e, no value entered for that model variable. When I put all values for the model class it returned success
In short - while calling toJson method, no values should be null

google map palace flutter

I'm trying to fetch nearby places in my app, but there is some error.
If there is same topic please notice me
I'm looking forward for your advice
void _searchNearby(double latitude, double longitude) async {
setState(() {
markers.clear();
});
String url =
'${googlePlaceURL}/json?location=${latitude},${longitude}&radius=1500&type=${placeType}&key=${mapAPI}';
print(url);
http.Response response = await http.get(url);
print('********'+'$response');
if (response.statusCode == 200) {
final data = json.decode(response.body);
print(data);
} else {
throw Exception('An error occurred getting places nearby');
}
}
Error:
I/flutter (10208): https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.4219983,-122.084&radius=1500&type=subway_station&key=AIzaSyAjclu-U5mgWji4rENX0LxvrfYXljfK5pg
E/flutter (10208): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Scheme not starting with alphabetic character (at character 1)
E/flutter (10208): https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.4...
E/flutter (10208): ^
E/flutter (10208):
E/flutter (10208): #0 _Uri._fail (dart:core/uri.dart:1623:5)
E/flutter (10208): #1 _Uri._makeScheme (dart:core/uri.dart:2184:7)
E/flutter (10208): #2 new _Uri.notSimple (dart:core/uri.dart:1465:18)
E/flutter (10208): #3 Uri.parse (dart:core/uri.dart:1022:17)
E/flutter (10208): #4 BaseClient._sendUnstreamed (package:http/src/base_client.dart:152:34)
E/flutter (10208): <asynchronous suspension>
E/flutter (10208): #5 BaseClient.get (package:http/src/base_client.dart:32:7)
E/flutter (10208): #6 get.<anonymous closure> (package:http/http.dart:46:36)
E/flutter (10208): #7 _withClient (package:http/http.dart:166:20)
E/flutter (10208): <asynchronous suspension>
E/flutter (10208): #8 get (package:http/http.dart:46:5)
E/flutter (10208): #9 MapSampleState._searchNearby (package:flutter_course/Map/map.dart:44:36)
E/flutter (10208): <asynchronous suspension>
E/flutter (10208): #10 MapSampleState.build.<anonymous closure> (package:flutter_course/Map/map.dart:119:11)
It looks like the variable googlePlaceURL start with space. Check it out, I think you can solve it in an easy way.

Dart Object -> JSON String failing to convert to JSON

I'm trying to serialize an object to JSON and then back from JSON to object again.
This is the code snippet that is supposed to give me proper JSON:
LoginRequest req = new LoginRequest();
req.username = username;
req.password = password;
req.created = 123456;
req.test = "KOTS";
print(req.toString());
What I'm seeing in the console is this:
{} (:1)
In pubspec.yaml I'm importing json_object as a dependency:
environment:
sdk: '>=1.0.0 <2.0.0'
dependencies:
...
json_object: any
I have a base message class that extends JsonObject:
import 'package:json_object/json_object.dart';
class Message extends JsonObject {
int created = new DateTime.now().millisecondsSinceEpoch;
}
and then I have a LoginRequest that extends Message:
import 'Message.dart';
class LoginRequest extends Message {
String _username;
String _password;
String test;
String get username => _username;
set username(String username) {
_username = username.trim();
}
String get password => _password;
set password(String password) {
_password = password.trim();
}
}
I was thinking that only the base class will be converting to Json, so I wrote another test case:
Message msg = new Message();
msg.created = 123456;
print(msg.toString());
This is also printing:
{} (:1)
Calling objectToJson does the same:
objectToJson(msg).then((jsonStr) => print(jsonStr));
objectToJson(req).then((jsonStr) => print(jsonStr));
Outputs:
{}
{}
Removing extends JsonObject causes the above code to spew a stack trace:
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0 _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3 JsonEncoder.convert (dart:convert/json.dart:243)
#4 JsonCodec.encode (dart:convert/json.dart:141)
#5 login (package:falm/login-dialog.dart:47:22)
#6 Function.apply (dart:core-patch/function_patch.dart:28)
#7 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8 invoke (package:smoke/smoke.dart:43:41)
#9 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.
NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2 objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3 objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4 login (package:falm/login-dialog.dart:43:17)
#5 Function.apply (dart:core-patch/function_patch.dart:28)
#6 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7 invoke (package:smoke/smoke.dart:43:41)
#8 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Clicked Login (:1)
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0 _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3 JsonEncoder.convert (dart:convert/json.dart:243)
#4 JsonCodec.encode (dart:convert/json.dart:141)
#5 login (package:falm/login-dialog.dart:47:22)
#6 Function.apply (dart:core-patch/function_patch.dart:28)
#7 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8 invoke (package:smoke/smoke.dart:43:41)
#9 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.
NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2 objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3 objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4 login (package:falm/login-dialog.dart:44:17)
#5 Function.apply (dart:core-patch/function_patch.dart:28)
#6 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7 invoke (package:smoke/smoke.dart:43:41)
#8 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Importing dart:convert and using JSON.encode does the same:
import 'dart:convert' show JSON;
...
print(JSON.encode(msg));
print(JSON.encode(req));
Outputs:
{}
{}
If I remove the extends JsonObject, then it throws a stack trace:
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0 _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3 JsonEncoder.convert (dart:convert/json.dart:243)
#4 JsonCodec.encode (dart:convert/json.dart:141)
#5 login (package:falm/login-dialog.dart:47:22)
#6 Function.apply (dart:core-patch/function_patch.dart:28)
#7 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8 invoke (package:smoke/smoke.dart:43:41)
#9 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.
NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2 objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3 objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4 login (package:falm/login-dialog.dart:43:17)
#5 Function.apply (dart:core-patch/function_patch.dart:28)
#6 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7 invoke (package:smoke/smoke.dart:43:41)
#8 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Clicked Login (:1)
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0 _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1 _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2 _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3 JsonEncoder.convert (dart:convert/json.dart:243)
#4 JsonCodec.encode (dart:convert/json.dart:141)
#5 login (package:falm/login-dialog.dart:47:22)
#6 Function.apply (dart:core-patch/function_patch.dart:28)
#7 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8 invoke (package:smoke/smoke.dart:43:41)
#9 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
Is JsonObject still the right way to go for serializing objects to JSON and deserializing JSON to objects? (I see in the code copyright 2013 which is ancient by now). If so, am I missing something in my classes?
In the dart cookbook there are examples where every class has its own toJson method and where all the values are manually copied into a map, this is cumbersome, if my whole app is JSON-driven, then I'll be spending most of my time writing boilerplate toJson / fromJson methods - this is exactly what I'm trying to get away from, hence the reason for choosing dart.
Furthermore I see examples on StackOverflow where mirrors are being used followed by comments that mirrors aren't fully supported in dart2js - since this is a browser based application, it is crucial that it can compile to javascript.
Update:
Based on Robert's answer, it seems doing the boilerplate is unavoidable:
Message.dart
import 'dart:convert' show JSON;
class Message {
int created = new DateTime.now().millisecondsSinceEpoch;
Map toJson() {
Map map = new Map();
map["created"] = this.created;
return map;
}
String toString(){
return JSON.encode(this);
}
}
LoginRequest.dart
import 'Message.dart';
class LoginRequest extends Message {
String _username;
String _password;
String test;
String get username => _username;
set username(String username) {
_username = username.trim();
}
String get password => _password;
set password(String password) {
_password = password.trim();
}
Map toJson() {
Map map = super.toJson();
map["username"] = this.username;
map["password"] = this.password;
return map;
}
}
Test code:
LoginRequest req = new LoginRequest();
req.username = username;
req.password = password;
req.created = 123456;
req.test = "KOTS";
print(req);
// outputs: {"created":123456,"username":"asdfasdf","password":"adfasdf"} (:1)
Message msg = new Message();
msg.created = 123456;
print(msg);
// outputs: {"created":123456} (:1)
toString I only need to implement once on the Message class, toJson will need to go on every class.
I think your problem is that you use print(req.toString());. Have you tried to do this:
objectToJson(req).then((jsonStr) => print(jsonStr)); Maybe this gives you a json string.
I personally feel like you actually SHOULD provide a toJson/toObject method because you have full control over what is serialized and how it is serialized (e.g. exclude private fields, null values, ...).
// EDIT
Because you use extends JsonObject toString() returns an empty map.
// EDIT
https://code.google.com/p/dart/issues/detail?id=6490 doesn't look like it is supported well. But then you can't use the json_object package anyway.
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'. This should be because the package requires experimental mirror features.
Using JSON.encode you cannot put an object into there. See https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:convert.JsonCodec#id_encode :
Either you specify the second parameter or implement .toJson().