crystal-json-demo
Crystal JSON 处理示例
这个 demo 展示了如何使用 Crystal 的 JSON 模块处理 JSON 数据。
概念
Crystal 标准库提供了 JSON 模块,可以方便地解析和生成 JSON 数据。
main.cr
require "json"
# ===== 1. 解析 JSON 字符串 =====
puts "===== 1. 解析 JSON 字符串 ====="
json_str = <<-JSON
{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"skills": ["Nim", "Python", "Rust"],
"address": {
"city": "Beijing",
"country": "China"
},
"active": true
}
JSON
parsed = JSON.parse(json_str)
puts "姓名: #{parsed["name"].as_s}"
puts "年龄: #{parsed["age"].as_i}"
puts "邮箱: #{parsed["email"].as_s}"
puts "技能: #{parsed["skills"].as_a.map(&.as_s)}"
puts "城市: #{parsed["address"]["city"].as_s}"
puts "活跃: #{parsed["active"].as_bool}"
# ===== 2. 构建 JSON 对象 =====
puts "\n===== 2. 构建 JSON 对象 ====="
user = JSON::Builder.new(IO::Memory.new)
user do
object do
field "name", "Bob"
field "age", 25
field "skills" do
array do
push "Go"
push "Rust"
push "C++"
end
end
field "active", false
end
end
puts "生成的 JSON:"
puts user.to_s
# ===== 3. JSON 映射到类 =====
puts "\n===== 3. JSON 映射到类 ====="
class Person
include JSON::Serializable
property name : String
property age : Int32
property email : String?
end
json_data = %({"name": "Carol", "age": 28, "email": "carol@example.com"})
person = Person.from_json(json_data)
puts "姓名: #{person.name}"
puts "年龄: #{person.age}"
puts "邮箱: #{person.email}"
# ===== 4. 复杂对象映射 =====
puts "\n===== 4. 复杂对象映射 ====="
class Address
include JSON::Serializable
property city : String
property country : String
end
class Employee
include JSON::Serializable
property name : String
property age : Int32
property address : Address?
end
employee_json = <<-JSON
{
"name": "David",
"age": 35,
"address": {
"city": "Shanghai",
"country": "China"
}
}
JSON
employee = Employee.from_json(employee_json)
puts "员工: #{employee.name}"
puts "年龄: #{employee.age}"
puts "城市: #{employee.address.try &.city}"
# ===== 5. 数组处理 =====
puts "\n===== 5. 数组处理 ====="
numbers_json = "[1, 2, 3, 4, 5]"
numbers = JSON.parse(numbers_json).as_a
sum = 0
numbers.each do |n|
sum += n.as_i
end
puts "数组: #{numbers.map(&.as_i)}"
puts "和: #{sum}"
# ===== 6. 类型安全的序列化 =====
puts "\n===== 6. 类型安全的序列化 ====="
class Config
include JSON::Serializable
property debug : Bool = false
property timeout : Int32 = 30
property servers : Array(String) = [] of String
end
config = Config.from_json(%({"debug": true, "timeout": 60, "servers": ["srv1", "srv2"]}))
config_json = config.to_json
puts "配置 JSON: #{config_json}"
# ===== 7. 处理嵌套数组 =====
puts "\n===== 7. 处理嵌套数组 ====="
matrix_json = "[[1,2,3],[4,5,6],[7,8,9]]"
matrix = JSON.parse(matrix_json).as_a
matrix.each_with_index do |row, i|
row_arr = row.as_a
puts "行 #{i}: #{row_arr.map(&.as_i).join(", ")}"
end
Repository
crystal-json-demo
Owner
Statistic
- 0
- 0
- 0
- 0
- 0
- 29 days ago
- March 16, 2026
License
Links
Synced at
Mon, 16 Mar 2026 00:33:06 GMT
Languages