序列化 #

一、内置序列化 #

1.1 Serialization模块 #

julia
using Serialization

data = Dict("a" => 1, "b" => [1, 2, 3])

serialize("data.ser", data)

loaded = deserialize("data.ser")

1.2 注意事项 #

  • Julia内置序列化不保证版本兼容
  • 适合临时存储和进程间通信

二、JLD2 #

2.1 安装 #

julia
using Pkg
Pkg.add("JLD2")

2.2 基本使用 #

julia
using JLD2

data = Dict("x" => [1, 2, 3], "y" => "hello")

jldsave("data.jld2"; data...)

loaded = load("data.jld2")

2.3 保存多个变量 #

julia
using JLD2

x = 10
y = [1, 2, 3]
z = "hello"

jldsave("variables.jld2"; x, y, z)

loaded = load("variables.jld2")
loaded["x"]
loaded["y"]

2.4 追加数据 #

julia
using JLD2

jldopen("data.jld2", "a+") do f
    f["new_var"] = 100
end

三、JSON #

3.1 安装 #

julia
using Pkg
Pkg.add("JSON3")

3.2 基本使用 #

julia
using JSON3

data = Dict("name" => "Julia", "version" => 1.10)

json_str = JSON3.write(data)

parsed = JSON3.read(json_str)

3.3 文件操作 #

julia
using JSON3

data = Dict("items" => [1, 2, 3], "count" => 3)

open("data.json", "w") do f
    JSON3.pretty(f, data)
end

parsed = open("data.json", "r") do f
    JSON3.read(f)
end

3.4 结构体序列化 #

julia
using JSON3

struct Person
    name::String
    age::Int
end

p = Person("Alice", 25)

json_str = JSON3.write(p)

parsed = JSON3.read(json_str, Person)

四、其他格式 #

4.1 TOML #

julia
using Pkg
Pkg.add("TOML")

using TOML

data = Dict("database" => Dict("host" => "localhost", "port" => 5432))

open("config.toml", "w") do f
    TOML.print(f, data)
end

config = TOML.parsefile("config.toml")

4.2 YAML #

julia
using Pkg
Pkg.add("YAML")

using YAML

data = Dict("name" => "Julia", "features" => ["fast", "easy"])

YAML.write_file("config.yaml", data)

loaded = YAML.load_file("config.yaml")

4.3 MessagePack #

julia
using Pkg
Pkg.add("MsgPack")

using MsgPack

data = Dict("a" => 1, "b" => [2, 3, 4])

packed = MsgPack.pack(data)

unpacked = MsgPack.unpack(packed)

五、实践练习 #

5.1 练习1:配置管理 #

julia
using JSON3

struct AppConfig
    host::String
    port::Int
    debug::Bool
end

function save_config(filename, config::AppConfig)
    open(filename, "w") do f
        JSON3.pretty(f, config)
    end
end

function load_config(filename)
    open(filename, "r") do f
        JSON3.read(f, AppConfig)
    end
end

config = AppConfig("localhost", 8080, false)
save_config("config.json", config)
loaded = load_config("config.json")

5.2 练习2:数据缓存 #

julia
using JLD2

function cached_compute(key, compute_func; cache_file="cache.jld2")
    if isfile(cache_file)
        cache = load(cache_file)
        if haskey(cache, key)
            return cache[key]
        end
    end
    
    result = compute_func()
    
    cache = isfile(cache_file) ? load(cache_file) : Dict{String, Any}()
    cache[key] = result
    jldsave(cache_file; cache...)
    
    return result
end

result = cached_compute("expensive_op") do
    sleep(2)
    rand(1000)
end

5.3 练习3:数据导出 #

julia
using JSON3, CSV, DataFrames

function export_data(data, filename)
    ext = splitext(filename)[2]
    
    if ext == ".json"
        open(filename, "w") do f
            JSON3.pretty(f, data)
        end
    elseif ext == ".csv"
        df = DataFrame(data)
        CSV.write(filename, df)
    else
        error("Unsupported format: $ext")
    end
end

data = Dict("name" => ["Alice", "Bob"], "age" => [25, 30])
export_data(data, "output.json")
export_data(data, "output.csv")

六、总结 #

本章我们学习了:

  1. 内置序列化:Serialization模块
  2. JLD2:Julia原生格式
  3. JSON:通用数据交换格式
  4. 其他格式:TOML、YAML、MessagePack

接下来让我们学习Julia的并发编程!

最后更新:2026-03-27