Back to results for “JSON”
Flutter › JSON Serialization & Deserialization

How can you properly implement genuinely custom JSON converters specifically for a given specific type that json_serializable does not already directly know exactly how to properly handle by default, such as converting a DateTime value to and from a specific particular custom string format?

Advanced

Answer

For a genuinely specific type that json_serializable's own default built in conversion logic does not already directly and correctly handle appropriately, such as needing a DateTime value properly converted to and from a genuinely very specific particular custom string format rather than its own considerably more generic default ISO format, you can properly write your own genuinely fully custom JsonConverter class defining exactly how that specific particular type should genuinely be converted in both directions, then simply annotate the genuinely relevant particular field with that specific custom converter, letting json_serializable's own code generation properly and correctly use your own genuinely custom logic specifically for that one particular field.
class UnixTimestampConverter implements JsonConverter<DateTime, int> {
  const UnixTimestampConverter();
  @override
  DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json * 1000);
  @override
  int toJson(DateTime object) => object.millisecondsSinceEpoch ~/ 1000;
}
Real-world example A weather app receives timestamps from its particular backend API formatted as raw Unix timestamps rather than a genuinely standard ISO date string, and properly implements a custom JsonConverter specifically to correctly convert that particular specific format to and from a genuinely proper usable Dart DateTime object.

Common follow-ups: What genuinely other common types typically require this kind of genuinely custom JSON converter?;How do you actually properly apply a genuinely custom converter consistently across every single field of that exact same specific particular type throughout an entire given model class?