Dart changing json property name when serializing

json_serializable is a dart library for converting dynamic json object into a typed object. Sometimes the properties from the raw json data comes in with snake_case, but by convention the class properties in dart should use camelCase. The following is an example to change the property names of json data when serializing it using the json_serializable library.

1. The json data to be serialized. stock.json

{
 "daily_high": 99,
 "daily_low": 90
}

2. Changing the property name in the class model via @JsonKey annotation. Stock.dart

import 'package:json_annotation/json_annotation.dart';

part 'stock.g.dart';

@JsonSerializable()
class Stock {
  /// Using the @JsonKey to change the property daily_high to dailyHigh
  @JsonKey(name: 'daily_high')
  final int dailyHigh;

  /// Using the @JsonKey to change the property daily_low to dailyLow
  @JsonKey(name: 'daily_low')
  final int dailyLow;


  Stock({required this.dailyHigh, required this.dailyLow});

  /// Connect the generated [_$StockFromJson] function to the `fromJson`
  /// factory.
  factory Stock.fromJson(Map json) => _$StockFromJson(json);

  /// Connect the generated [_$StockToJson] function to the `toJson` method.
  Map toJson() => _$StockToJson(this);
}

3. Converting the dynamic json to typed json normally with json_serializable

const String jsonStr = "{\"daily_high\": 99,\"daily_low\": 90}";
Map data = await json.decode(jsonStr);
Stock stock = Stock.fromJson(data);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search