90 lines
2.4 KiB
Plaintext
90 lines
2.4 KiB
Plaintext
|
|
{# 反序列化器模板 #}
|
||
|
|
{% if part == 'header' %}
|
||
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <vector>
|
||
|
|
#include <cstdint>
|
||
|
|
#include <string>
|
||
|
|
|
||
|
|
/**
|
||
|
|
* {{ source_message.full_name }}消息结构
|
||
|
|
*/
|
||
|
|
struct {{ source_message.system_name }}{{ source_message.message_type }} {
|
||
|
|
{% for field in source_message.fields %}
|
||
|
|
{{ field.type.value }} {{ field.name }}; // {{ field.description }}
|
||
|
|
{% endfor %}
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 反序列化器
|
||
|
|
* 将字节流反序列化为{{ source_message.full_name }}消息
|
||
|
|
*/
|
||
|
|
class Deserializer {
|
||
|
|
public:
|
||
|
|
Deserializer();
|
||
|
|
|
||
|
|
// 反序列化
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }} deserialize(
|
||
|
|
const std::vector<uint8_t>& data);
|
||
|
|
|
||
|
|
private:
|
||
|
|
{% if serialization.value == 'json' %}
|
||
|
|
// JSON反序列化
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }} deserializeJson(
|
||
|
|
const std::string& json_str);
|
||
|
|
{% elif serialization.value == 'xml' %}
|
||
|
|
// XML反序列化
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }} deserializeXml(
|
||
|
|
const std::string& xml_str);
|
||
|
|
{% endif %}
|
||
|
|
};
|
||
|
|
|
||
|
|
{% else %}
|
||
|
|
#include "deserializer.h"
|
||
|
|
#include <sstream>
|
||
|
|
#include <stdexcept>
|
||
|
|
|
||
|
|
{% if serialization.value == 'json' %}
|
||
|
|
#include <nlohmann/json.hpp>
|
||
|
|
using json = nlohmann::json;
|
||
|
|
{% endif %}
|
||
|
|
|
||
|
|
Deserializer::Deserializer() {
|
||
|
|
}
|
||
|
|
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }}
|
||
|
|
Deserializer::deserialize(const std::vector<uint8_t>& data) {
|
||
|
|
{% if serialization.value == 'json' %}
|
||
|
|
std::string json_str(data.begin(), data.end());
|
||
|
|
return deserializeJson(json_str);
|
||
|
|
{% else %}
|
||
|
|
// 默认二进制反序列化
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }} message;
|
||
|
|
// TODO: 实现二进制反序列化逻辑
|
||
|
|
return message;
|
||
|
|
{% endif %}
|
||
|
|
}
|
||
|
|
|
||
|
|
{% if serialization.value == 'json' %}
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }}
|
||
|
|
Deserializer::deserializeJson(const std::string& json_str) {
|
||
|
|
{{ source_message.system_name }}{{ source_message.message_type }} message;
|
||
|
|
|
||
|
|
try {
|
||
|
|
json j = json::parse(json_str);
|
||
|
|
|
||
|
|
{% for field in source_message.fields %}
|
||
|
|
if (j.contains("{{ field.name }}")) {
|
||
|
|
message.{{ field.name }} = j["{{ field.name }}"];
|
||
|
|
}
|
||
|
|
{% endfor %}
|
||
|
|
|
||
|
|
} catch (const std::exception& e) {
|
||
|
|
throw std::runtime_error("JSON deserialization failed: " + std::string(e.what()));
|
||
|
|
}
|
||
|
|
|
||
|
|
return message;
|
||
|
|
}
|
||
|
|
{% endif %}
|
||
|
|
{% endif %}
|