我cJSON
结合使用 JNI 在我的 Java 和 C 组件之间来回传递 JSON 数据。
我是 C 的新手并且自学,所以请耐心等待。
cJSON
有一个很好的函数,cJSON->Print
它将 JSON 结构转换为字符串表示。这很好,除了字符串是“JSON Pretty”格式,所有换行符和制表符都完好无损。我不需要这些,因为我的应用程序不显示 JSON,它只是将它用于数据传输。所以,我正在尝试编写一个函数来删除那些多余的字符。
void json_clean(char *buffer, const char *pretty) {
int count = 0;
for(int i = 0; i < strlen(pretty); i++) {
if(pretty[i] == '\n' || pretty[i] == '\t')
continue;
buffer[count] = pretty[i];
count++;
}
int last = strlen(buffer) - 1;
buffer[last] = '\0';
}
这有效地删除了\n
and\t
字符就好了,但有时最后我会得到一些垃圾字符,比如6
or ?
,这让我认为这是一个空终止问题。
printf
在 C 中使用并在 Java 中打印时,字符串的输出方式相同。
NUL
在调用函数之前,我确保为字符分配的字节比我需要的多一个字节:
// get the pretty JSON
const char *pretty = cJSON_Print(out);
// how many newlines and tabs?
int count = 0;
for(int i = 0; i < strlen(pretty); i++) {
if(pretty[i] == '\n' || pretty[i] == '\t')
count++;
}
// make new buffer, excluding these chars
char *newBuf = malloc((strlen(pretty) - count) + 1); // +1 for null term.
json_clean(newBuf, pretty);
// copy into new Java string
jstring retVal = (*env)->NewStringUTF(env, newBuf);
free(newBuf); // don't need this anymore
任何帮助是极大的赞赏。