【问题标题】:C : struct to json stringC:结构到 json 字符串
【发布时间】:2016-01-05 21:46:11
【问题描述】:

我想将 struct 转换为 json 字符串,可以吗? 例如:

struct data{
   int a;
   int b;
}
struct data myData;
myData.a = 1;
myData.b = 2;

char* structToString(struct data myData){
    ......
}

output:
     myData{
         a : 1,
         b : 2,
     }

如何实现这个函数(structToString)?

【问题讨论】:

  • 嗯....你必须为它写代码?
  • 编写函数自己做。或者使用公开的 json C 库的分数。

标签: c json struct


【解决方案1】:

您也可以查看cisson。以下来自他们的 README 的示例非常简单,可以实现您正在寻找的内容:

让我们把下面的C对象转成JSON

struct foo = {
  .foo = "bar",
  .array = {1, 2, 3},
  .question = true
};
#define CISSON_IMPLEMENTATION
#include "cisson.h"

int main(void) {
    struct tree tree = {0};
    
    START_AND_PUSH_TOKEN(&tree, ROOT, "#custom root");
    /* every token we push will be bound to the current root */
    START_AND_PUSH_TOKEN(&tree, OBJECT, "{");
    PUSH_ROOT(&tree);
    /* "PUSH_ROOT" will change the current root to the previously
     * pushed token so every following
     * token will be bound to the object token */
    START_AND_PUSH_TOKEN(&tree, STRING, "\"foo\"");
    PUSH_ROOT(&tree);
    /* next token will be bound to the key */
    START_AND_PUSH_TOKEN(&tree, STRING, "\"bar\"");
    CLOSE_ROOT(&tree);
    /* now the root is no more the key but the object */
    START_AND_PUSH_TOKEN(&tree, STRING, "\"array\"");
    PUSH_ROOT(&tree);
    START_AND_PUSH_TOKEN(&tree, ARRAY, "[");
    PUSH_ROOT(&tree);
    START_AND_PUSH_TOKEN(&tree, NUMBER, "1");
    START_AND_PUSH_TOKEN(&tree, NUMBER, "2");
    START_AND_PUSH_TOKEN(&tree, NUMBER, "3");
    CLOSE_ROOT(&tree); /* the array */
    CLOSE_ROOT(&tree); /* the object property */
    START_AND_PUSH_TOKEN(&tree, STRING, "\"question\"");
    PUSH_ROOT(&tree);
    START_AND_PUSH_TOKEN(&tree, TRUE, "true");
    puts(to_string(&tree)); /* {"foo":"bar","array":[1,2,4],"question":true} */
}

【讨论】:

    【解决方案2】:

    免责声明:我是项目的所有者https://github.com/tamask1s/zax-parser

    在库的帮助下,如果您提供有关需要转换为 JSON 的结构成员的元信息,您就可以拥有这样的功能。

    这个库很不成熟,因为我已经实现了我只需要的功能,但是你可以用更多的功能扩展它,或者你可以将它作为灵感。你需要一个 c++11 编译器才能编译。

    struct data
    {
        int x = 7;
        string name = "seven";
    };
    
    #define some_json_props JSON_PROPERTY(x), JSON_PROPERTY(name)
    
    data some_obj;
    
    char json_string[1000];
    
    zax_convert_to_json(json_string, sizeof(json_string), some_obj, some_json_props);
    

    json_string 的值为:{"x":7, "name":"seven"}

    【讨论】:

      【解决方案3】:

      是的,很有可能。

      JSON 对象只不过是具有特定格式的字符串。您将需要为您的字符串分配内存,并用需要在其中的各种元素填充它。使用strcat() 函数可以轻松“填充”您的字符串。

      您的 JSON 对象以“{”开头。然后变量按以下格式列出:

      "variable_name":"value"
      

      每个变量都用逗号分隔。对象以“}”结尾。

      使用这个,你应该可以自己做..

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 2014-04-28
        • 1970-01-01
        • 2011-08-11
        • 2011-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        相关资源
        最近更新 更多