首页 > 解决方案 > 如何在c中以优雅的方式将json转换为struct

问题描述

有一个json和一个结构:

json:

{
    "zone":12
    "id":1
    "rule":8
    "name":"jsontest"
}

结构:

strict foo
{
    int Zone;
    int Id;
    uint8_t Rule;
    char Name[32];
}

我创建了一个映射来将 json 转换为 struct:

map[]
{
    /* label   key   func*/
    {Zone, "zone", JsonSafeGetInt},
    {Rule, "rule", JsonSafeGetInt},
    {Id, "id", JsonSafeGetInt},
    {Name, "name", JsonSafeGetString}
}

我想使用地图将 json 转换为 struct:

strict foo *fooPtr;
for (i = 0; i< MapSize; i++)
{
    fooPtr->map[i].label = map[i].func(xxx);
}

但是我不知道它是否可以实现,因为我不知道如何用C编写这样的代码。

标签: cjson

解决方案


推荐阅读