- Creative Projects for Rust Programmers
- Carlo Milanesi
- 361字
- 2021-06-18 19:02:00
Returning JSON data
The previous section returned data in plain text. This is unusual in a web service and rarely satisfactory. Usually, web services return data in JSON, XML, or another structured format. The json_db project is identical to the memory_db project, except for its returning data in the JSON format.
First of all, let's see what happens when the same curl commands from the previous section are executed on it, as follows:
- The insertions have the same behavior because they just printed a number.
- The first query should print the following: [1,2,3]. The three numbers are in an array, and so they are enclosed in brackets.
- The second query should print the following: "Mary Jane". The name is a string, and so it is enclosed in quotation marks.
- The third query should print the following: [[2,"Jonathan"],[3,"Mary Jane"]]. The sequence of persons is an array of two records, and each of them is an array of two values, which are a number and a string.
Now, let's see the differences in the code of this project with respect to the previous one.
In the Cargo.toml file, one dependency has been added, as follows:
serde_json = "1.0"
This is needed to serialize the data in JSON format.
In the main.rs file, the get_all_persons_ids function (instead of returning simply a string) has the following code:
HttpResponse::Ok()
.content_type("application/json")
.body(
json!(db_conn.get_all_persons_ids().collect::<Vec<_>>())
.to_string())
First, a response with a status code Ok is created; then, its content type is set to application/json, to let the client know how to interpret the data it will receive; and lastly, its body is set, using the json macro taken from the serde_json crate. This macro takes an expression—in this case, with type, Vec<Person>—and returns a serde_json::Value value. Now, we need a string, and so to_string() is called. Notice that the json! macro requires its argument to implement the Serialize trait or to be convertible into a string.
The get_person_name_by_id, get_persons, and insert_person functions have similar changes. The main function has no changes. The db_access.rs files are identical.
- SQL Server 從入門到項目實踐(超值版)
- TypeScript Essentials
- Learning C# by Developing Games with Unity 2020
- Docker進(jìn)階與實戰(zhàn)
- 從0到1:HTML+CSS快速上手
- SQL語言從入門到精通
- OpenShift在企業(yè)中的實踐:PaaS DevOps微服務(wù)(第2版)
- 實戰(zhàn)Java高并發(fā)程序設(shè)計(第3版)
- 零基礎(chǔ)輕松學(xué)SQL Server 2016
- Java EE 7 Performance Tuning and Optimization
- PySide 6/PyQt 6快速開發(fā)與實戰(zhàn)
- Mastering Business Intelligence with MicroStrategy
- AIRIOT物聯(lián)網(wǎng)平臺開發(fā)框架應(yīng)用與實戰(zhàn)
- Geospatial Development By Example with Python
- Vue.js 3應(yīng)用開發(fā)與核心源碼解析