我从使用Golang进行编程开始,事情看起来很简单。然后我偶然发现了C(JSMN)的JSON解析器,以便可以尝试CGO。
static const char *JSON_STRING =
"{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
"\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
printf("- User: %.*s\n", t[i+1].end-t[i+1].start, JSON_STRING + t[i+1].start);
这给了我结果:
“-用户:johndoe”
我是C的新手。我想将值“ johndoe” 放入变量中。我在下面的代码中尝试了NULL
:
int c = 0;
char sub[1000];
while (c < (t[i+1].end-t[i+1].start) ) {
sub[c] = JSON_STRING[t[i+1].start+c-1];
c++;
}
sub[c] = '\0';
输出:
“-用户:null”
我该怎么做?谢谢!
答案 0 :(得分:0)
您可以使用strncpy()将所需的字符串复制到一个单独的变量中,因为您已经知道了字符串的长度和起点,即:
t[i+1].end - t[i+1].start // length of the string to copy
JSON_STRING + t[i+1].start // starting point from where to start copying
例如:
const char* strStart = JSON_STRING + t[i+1].start;
const size_t strLength = t[i+1].end - t[i+1].start;
const size_t length = 8; // required to store "johndoe"
char strCopy[ length ] = { 0 };
strncpy( strCopy, strStart, strLength );
// You might need to null terminate your string
// depending upon your specific use case.
JSMN解析器存储令牌的开始和结束位置。要求图书馆的用户在需要时使用这些位置进行复制。
%.*s
中的 printf()
格式说明符将实际C样式字符串之前的字段宽度(要打印的字符串长度)作为参数。有关更多详细信息,请参见this。