首先,您需要找到有效载荷的开始。这是在找到空行之后。
然后您需要通过解析字符串json_loads
并收到一个根 JSON 对象。您要查找的数据存储在嵌入式对象"location"
中,您可以通过json_object_get
. 然后就可以解析内容了。这可以通过两种方式完成:
- 您可以使用格式字符串来解析该对象的成员或
- 您可以获取位置对象的子对象并检索每个子对象的值。
完成工作后,您需要减少引用计数器以允许释放对象。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jansson.h>
// gcc -o json-test `pkg-config --cflags jansson` json.c `pkg-config --libs jansson`
int main(void)
{
FILE *input = fopen("curl-data.txt","rt");
if (input == NULL) {
fprintf(stderr, "Cannot open curl-data.txt.\n");
return 1;
}
// sample data has 878 bytes.
char buffer[1024];
int num = fread(buffer, 1, sizeof(buffer)-1, input);
buffer[num]=0;
// In this example the payload format is known and we can directly search
// for the start. In HTTP packets header and payload are separated by an empty
// line and that can be used to search for start of payload.
char *data_start = strstr(buffer, "{");
if (data_start == NULL) {
fprintf(stderr, "did not find start of payload.\n");
return 1;
}
printf("Payload: ###\n%s\n###\n", data_start);
json_error_t err;
json_t *root = json_loads(data_start, 0, &err);
if (root == NULL) {
fprintf(stderr, "Failed to parse input string: %s\n", err.text);
return 1;
}
if (!json_is_object(root)) {
fprintf(stderr, "root is not an object\n");
json_decref(root);
return 1;
}
json_t *location = json_object_get(root, "location");
if (location == NULL || !json_is_object(location)) {
fprintf(stderr, "Location element not found or not an object\n");
json_decref(root);
return 1;
}
double lat, lng;
// alternative 1:
int res = json_unpack(location, "{s:f, s:f}", "lat", &lat, "lng", &lng);
if (res != 0) {
fprintf(stderr, "lat/lng elements not found\n");
json_decref(root);
return 1;
}
printf("1) lat: %f; lng: %f\n", lat, lng);
// alternative 2:
json_t *latval = json_object_get(location, "lat");
if (latval == NULL || !json_is_real(latval)) {
fprintf(stderr, "lat element not found or not a number\n");
json_decref(root);
return 1;
}
json_t *lngval = json_object_get(location, "lng");
if (lngval == NULL || !json_is_real(lngval)) {
fprintf(stderr, "lng element not found or not a number\n");
json_decref(root);
return 1;
}
lat = json_number_value(latval);
lng = json_number_value(lngval);
printf("2) lat: %f; lng: %f\n", lat, lng);
json_decref(root);
return 0;
}
我需要深入研究手册是否还需要减少其他 2 个对象的 refcounter。