ESP8266-移植cJSON到ESP8266

前端之家收集整理的这篇文章主要介绍了ESP8266-移植cJSON到ESP8266前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

由于ESP826自带的JSON API实在太难调用,就想着能不能自己移植一个JSON库。最近做STM32的时候正好需要移植JSON库,找了一下,找到了cJSON和Jansson。这篇文章是简单总结移植cJSON到ESP826要注意的事项。

移植步骤

首先到Github上下载cJSON代码https://github.com/DaveGamble/cJSON

然后我们只使用cJSONtest的源文件及头文件即可,导入到ESP8266工程里。

点击编译,自然会出现很多错误,下面简单说明一下。

  • 在cJSON.c里添加下面头文件,这些头文件是ESP8266专用的。
  • @H_404_21@
    #include "c_types.h"
    #include "osapi.h"
    #include "mem.h"
    #include "ets_sys.h"
    #include "osapi.h"
    • 注释掉cJSON_malloccJSON_free,用ESP8266自带os_mallocos_free代替,由于直接赋值会编译出错,所以用了宏定义的方式。
    • @H_404_21@
      #if 0
      static void *(*cJSON_malloc)(size_t sz) = os_malloc;
      static void (*cJSON_free)(void *ptr) = os_free;
      #else
      #define cJSON_malloc(sz) os_malloc(sz)
      #define cJSON_free(ptr) os_free(ptr)
      #endif

      其后,注释掉cJSON_InitHooks里面的内容,这个一般用不到所以注释掉也没关系。

      void ICACHE_FLASH_ATTR
      cJSON_InitHooks(cJSON_Hooks* hooks)
      {
      #if 0
          if (!hooks) { /* Reset hooks */
              cJSON_malloc = malloc;
              cJSON_free = free;
              return;
          }
      
          cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
          cJSON_free   = (hooks->free_fn)?hooks->free_fn:free;
      #endif
      }
      • 替换os_mallocos_free,还要替换printfmemsetmemcpy等等,请对照osapi.h里的内容替换。

      • 注释掉所有和浮点型有关的语句,ESP8266@R_301_472@浮点型,所以我们也不需要它,免得编译出错。例如注释下面的语句

      • @H_404_21@
        /* Parse the input text to generate a number,and populate the result into item. */
        static const char *ICACHE_FLASH_ATTR
        parse_number(cJSON *item,const char *num)
        {
            double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
        
            if (*num=='-') sign=-1,num++;   /* Has sign? */
            if (*num=='0') num++;           /* is zero */
            if (*num>='1' && *num<='9') do  n=(n*10.0)+(*num++ -'0');   while (*num>='0' && *num<='9'); /* Number? */
            if (*num=='.' && num[1]>='0' && num[1]<='9') {num++;        do  n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');}  /* Fractional part? */
            if (*num=='e' || *num=='E')     /* Exponent? */
            {   num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++;      /* With sign? */
                while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0');   /* Number? */
            }
        
            //注释掉这条语句
            //n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
        
            item->valuedouble=n;
            item->valueint=(int)n;
            item->type=cJSON_Number;
            return num;
        }

        同样,找到有fabs函数floor函数的语句,一并注释掉。
        注释掉导入float.h的语句。

猜你在找的Json相关文章