Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json内嵌子对象,我如何将子对象转为对应的结构体? #236

Open
DoIthd opened this issue Jan 5, 2024 · 5 comments
Open

Comments

@DoIthd
Copy link

DoIthd commented Jan 5, 2024

struct Info {
int idx;
std::string val;
};
REFLECTION(Info, idx, val);
std::string target;
target = R"({"version":1, "info": {"idx": 1, "val": "abc"}})";
iguana::jvalue res;
iguana::parse(res, target);
std::cout << res.at("version") << std::endl; // 这里可以获取到1
请问 我如何能够获取到info? 并将info 转为结构体Info?

@qicosmos
Copy link
Owner

qicosmos commented Jan 5, 2024

这样不是更简单么?

struct taget_t {
  int version;
  Info info;
};
REFLECTION(taget_t, version, info);

std::string str = R"({"version":1, "info": {"idx": 1, "val": "abc"}})";

taget_t t{};
iguana::from_json(str, t);

auto id = t.info.idx;

@qicosmos
Copy link
Owner

qicosmos commented Jan 5, 2024

如果用parse方式的话就没法转成结构体了,就要用jvalue了,参考https://github.com/qicosmos/iguana/blob/master/test/test.cpp#L198

@DoIthd
Copy link
Author

DoIthd commented Jan 7, 2024

这样不是更简单么?

struct taget_t {
  int version;
  Info info;
};
REFLECTION(taget_t, version, info);

std::string str = R"({"version":1, "info": {"idx": 1, "val": "abc"}})";

taget_t t{};
iguana::from_json(str, t);

auto id = t.info.idx;

感谢大佬回复,应用场景是这样的,对于Info, 不同版本可能会不一样,要根据version选择对应的结构体。

@qicosmos
Copy link
Owner

后面会支持部分解析,应该能满足你这个需求。

@bbbgan
Copy link
Collaborator

bbbgan commented Jan 21, 2024

抱歉,回复晚了,不同的info虽然有不一样的版本,但是只要不是冲突的就可以的,比如:

// 注册元信息
struct Info {
int idx;
std::string val;
std::string newval;
};
REFLECTION(Info, idx, val);
struct taget_t {
  int version;
  Info info;
};
REFLECTION(taget_t, version, info);
// 版本1
std::string str1 = R"({"version":1, "info": {"idx": 1, "val": "abc"}})";
taget_t t{};
iguana::from_json(st1, t);
// 版本2
std::string str2 = R"({"version":2, "info": {"idx": 1, "newval": "abc"}})";
taget_t t{};
iguana::from_json(str2, t);

之后会考虑冲突了应该如何处理,应该需要部分解析,或者延迟解析解决。

171930433 pushed a commit to 171930433/iguana that referenced this issue Jun 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants