JSON解析接口-C
# include <stdio.h>
# include <string.h> # define uint8_t unsigned char
# define uint32_t unsigned int
# define uint16_t unsigned short
# define REV_D "+IPD"
# define FUN_PAR_OVERFLOW 0xff
void buf_clear_0 ( uint8_t * data, uint8_t lenth)
{ int i= 0 ; for ( i= 0 ; i< lenth; i++ ) { if ( data[ i] == '\0' ) { data[ i] = ' ' ; } }
}
uint8_t find_char_len ( uint8_t * str, uint8_t c, uint16_t len)
{ int i= 0 ; for ( i= 0 ; i< len; i++ ) { if ( str[ i] == c) { return i; } } printf ( "FUN_PAR_OVERFLOW \r\n" ) ; return FUN_PAR_OVERFLOW;
}
uint8_t decode_cmd_data ( uint8_t * cmd, uint8_t * data, uint8_t * rev_data, int rev_data_len, uint8_t blank_on, uint8_t str_on)
{ char * tar_str= NULL ; int cmd_len= 0 ; char blank_len= 2 ; uint32_t val; if ( blank_on == 1 ) { blank_len++ ; } if ( str_on == 1 ) { blank_len++ ; } tar_str = ( char * ) strstr ( ( char * ) data, cmd) ; if ( tar_str != NULL ) { tar_str = & tar_str[ strlen ( cmd) + blank_len] ; if ( str_on == 1 ) { cmd_len = find_char_len ( ( uint8_t * ) tar_str, '"' , rev_data_len) ; if ( cmd_len == FUN_PAR_OVERFLOW) { return ; } memcpy ( rev_data, tar_str, cmd_len) ; } else { val = atoi ( tar_str) ; memcpy ( rev_data, & val, 4 ) ; } return 1 ; } else { printf ( "err\r\n" ) ; return 0 ; } }
void decode_cmd ( uint8_t * data)
{ uint8_t file_name[ 50 ] = { 0 } ; uint8_t file_ver[ 20 ] = { 0 } ; uint8_t file_size[ 20 ] = { 0 } ; uint8_t file_checksum[ 64 ] = { 0 } ; uint32_t dat_num= 0 ; if ( strstr ( data, "START_UPGRADE" ) ) { decode_cmd_data ( "file_name" , data, file_name, sizeof ( file_name) , 1 , 1 ) ; decode_cmd_data ( "version" , data, file_ver, sizeof ( file_ver) , 1 , 1 ) ; decode_cmd_data ( "file_size" , data, file_size, sizeof ( file_size) , 1 , 1 ) ; decode_cmd_data ( "checksum_check" , data, file_checksum, sizeof ( file_checksum) , 1 , 1 ) ; decode_cmd_data ( "data_num" , data, & dat_num, sizeof ( dat_num) , 0 , 0 ) ; } printf ( "file_name: %s\r\n" , file_name) ; printf ( "version: %s\r\n" , file_ver) ; printf ( "file_size: %s\r\n" , file_size) ; printf ( "checksum_check: %s\r\n" , file_checksum) ; printf ( "dat_num:%d\r\n" , dat_num) ; }
void decode_json ( uint8_t * data)
{ uint8_t * str; str = strstr ( data, REV_D) ; if ( str != NULL ) { buf_clear_0 ( str, 15 ) ; decode_cmd ( str) ; }
} char buf[ ] = "+IPD: receive:WBS-MYD-V10-00000001\
{\\"cmd\": \"START_UPGRADE\",\\"data\": {\\"version\": \"1.0\",\\"file_name\": \"V1.0.0.bin\",\\"file_size\": \"128537\",\\"checksum_check\": \"67f3b40ba0cbb7d289a9cf6f3f75e6c319f12bdc82d5c35\",\\"data_num\":132466\}\
}" ; int main ( )
{ decode_json ( buf) ; return 0 ; }