#define _POSIX_C_SOURCE 200809L #include #include #include #include "status.h" struct status *status_from_json(char *json_data) { json_t *root; json_error_t error; root = json_loads(json_data, 0, &error); if (!root) { fprintf(stderr, "status_from_json(): json parse error: line %d: %s\n", error.line, error.text); return NULL; } return status_from_json_t(root); } struct status *status_from_json_t(json_t *root) { struct status *s; if (!root) { fprintf(stderr, "status_from_json_t(): json data is null\n"); return NULL; } if (!json_is_object(root)) { fprintf(stderr, "status_from_json_t(): json root is not object\n"); json_decref(root); return NULL; } s = calloc(1, sizeof(struct status)); if (!s) { err(1, "status_from_json_t(): failed to allocate memory"); json_decref(root); return NULL; } json_t *id = json_object_get(root, "id"); if (json_is_string(id)) { s->id = strdup(json_string_value(id)); } json_t *uri = json_object_get(root, "uri"); if (json_is_string(uri)) { s->uri = strdup(json_string_value(uri)); } json_t *url = json_object_get(root, "url"); if (json_is_string(url)) { s->url = strdup(json_string_value(url)); } json_t *in_reply_to_id = json_object_get(root, "in_reply_to_id"); if (json_is_string(in_reply_to_id)) { s->in_reply_to_id = strdup(json_string_value(in_reply_to_id)); } json_t *in_reply_to_account_id = json_object_get(root, "in_reply_to_account_id"); if (json_is_string(in_reply_to_account_id)) { s->in_reply_to_account_id = strdup(json_string_value(in_reply_to_account_id)); } json_t *content = json_object_get(root, "content"); if (json_is_string(content)) { s->content = strdup(json_string_value(content)); } json_t *replies_count = json_object_get(root, "replies_count"); if (json_is_integer(replies_count)) { s->replies_count = json_integer_value(replies_count); } json_t *reblogs_count = json_object_get(root, "reblogs_count"); if (json_is_integer(reblogs_count)) { s->reblogs_count = json_integer_value(reblogs_count); } json_t *favourites_count = json_object_get(root, "favourites_count"); if (json_is_integer(favourites_count)) { s->favourites_count = json_integer_value(favourites_count); } json_decref(root); return s; } void status_free(struct status *s) { if (!s) { fprintf(stderr, "status_free(): status not initializes"); return; } if (s->id) free(s->id); if (s->uri) free(s->uri); if (s->url) free(s->url); if (s->in_reply_to_id != NULL) free(s->in_reply_to_id); if (s->in_reply_to_account_id) free(s->in_reply_to_account_id); if (s->reblog) status_free(s->reblog); if (s->content) free(s->content); free(s); }