#NCST202605H. Deserialize, then Serialize
Deserialize, then Serialize
题目描述
序列化和反序列化是开发中经常使用的技术,常出现于可持久化软件配置,发送网络请求,信息交换等场景,是现代计算机系统中不可或缺的一部分。
比如说我们有一本书
-
书的作者为
Robert-Sedgewick和Kevin-Wayne -
书的名字为 "Algorithm"
-
价格为 元
-
可以使用一个 元的优惠券
-
这本书还没有书评
-
这本书是可以被借阅的
我们规定,可以将其序列化成以下两种格式
TOML 格式
[book]
authors = ["Robert-Sedgewick", "Kevin-Wayne"]
name = "Algorithm"
price = 128
discount = 12.5
comments = []
can_borrow = true
特别规定,本题的TOML并非标准TOML,不会出现转义字符,内链表等高阶特性,仅会出现以下特性
-
对于结构名和等号左边的字段名,仅包含小写字母和下划线
-
对于等号右边的值,类型仅可能是整数型,实数型,布尔型(值为true或false),字符串和数组
-
对于一个数组,他所包含的元素的类型是相同的
-
一个数组可能为空数组
-
字符串中只会出现除
"和\外的ASCII可见字符
JSON 格式
{
"book": {
"authors": [
"Robert-Sedgewick",
"Kevin-Wayne"
],
"name": "Algorithm",
"price": 128,
"discount": 12.5,
"comments": [],
"can_borrow": true,
}
}
特别的,我们规定JSON中
-
只能使用四个字符宽度的缩进
-
每行末尾不能出现多余空格
-
对于一个数组,如果他有元素,必须换行打印
现在,给你一个TOML格式的字符串,请你转换成JSON格式(或者说给你一个字符串,反序列化TOML,再序列化成JSON)
输入格式
一共 行,每行一个字符串 ,表示给定的TOML格式数据
输出格式
序列化后的JSON格式数据
样例输入输出
[postgresql]
host = "localhost"
port = 5432
user = "postgres"
database = "app_db"
sslmode = "disable"
timezone = "UTC"
max_connections = 10
{
"postgresql": {
"host": "localhost",
"port": 5432,
"user": "postgres",
"database": "app_db",
"sslmode": "disable",
"timezone": "UTC",
"max_connections": 10
}
}
[rust]
version = "2026"
crate = ["serde", "toml", "serde_json"]
level = 3
reset = 3.5
dependencies = []
{
"rust": {
"version": "2026",
"crate": [
"serde",
"toml",
"serde_json"
],
"level": 3,
"reset": 3.5,
"dependencies": []
}
}
提示
我们题目里没有给定说我们有几行字符串,所以输入可能有点困难,这里我们提供一个一口气把所有输入读进来的方法
# Python
import sys
data = "".join(sys.stdin.readlines())
/* C 语言 */
#include <stdio.h>
#include <string.h>
char inputs[1000005];
void readlines() {
for (int begin = 0; begin != -1;) {
char *p = fgets(&inputs[begin], 1005, stdin);
if (p != NULL) {
begin += strlen(p);
} else
begin = -1;
}
}
// C++
#include<iostream>
#include<sstream>
std::string readlines() {
std::string line;
std::stringstream ss;
while (std::getline(std::cin, line))
ss << line;
return ss.str();
}