Skip to content

Commit 9d23d33

Browse files
author
Marcus Twichel
authored
docs(README): Response.json improvements (#77)
1 parent eed330f commit 9d23d33

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,36 @@ Response onRequest(RequestContext context) {
144144
}
145145
```
146146

147+
We can also return any Dart object in the `body` of the `Response.json` constructor and it will be serialized correctly as long as it has a `toJson` method that returns a `Map<String, dynamic>`.
148+
149+
💡 _Tip: Check out [json_serializable](https://pub.dev/packages/json_serializable) to automate the `toJson` generation_.
150+
151+
```dart
152+
import 'package:json_annotation/json_annotation.dart';
153+
154+
part 'user.g.dart';
155+
156+
@JsonSerializable()
157+
class User {
158+
const User({required this.name, required this.age});
159+
160+
final String name;
161+
final int age;
162+
163+
Map<String, dynamic> toJson() => _$UserToJson(this);
164+
}
165+
```
166+
167+
```dart
168+
import 'package:dart_frog/dart_frog.dart';
169+
170+
Response onRequest(RequestContext context) {
171+
return Response.json(
172+
body: User(name: 'Dash', age: 42),
173+
);
174+
}
175+
```
176+
147177
Route handlers can be synchronous or asynchronous. To convert the above route handlers to async, we just need to update the return type from `Response` to `Future<Response>`. We can add the `async` keyword in order to `await` futures within our handler before returning a `Response`.
148178

149179
```dart

0 commit comments

Comments
 (0)