On Wed, Aug 15, 2012 at 5:42 AM, Even Rouault <
even.r...@gmail.com> wrote:
> In the end, I'm happy with the serializer approach or the
> json_object_new_double_with_str(). What would you prefer ?
I think I prefer the serializer approach.
> As far as primitive types are concerned, I didn't see how a string or an
> integer or a boolean could be represented differently (and still using
> correct JSON formatting) than their default serializing.
Well, I'm expecting that a facility like this could also be used in
those cases where you need to go a bit beyond the standard JSON format
due to your specific application requirements.
>> int my_json_double_to_json_string(struct json_object *jso, struct
>> printbuf *pb, int level, int flags)
>> {
>> return sprintfbuf(pb, "%.2f", json_object_get_double(jso));
>> }
>>
>> ...
>> json_object *jso = json_object_new_double(123.456789);
>> json_object_set_serializer(jso, my_json_double_to_json_string);
>>
>> printf("%s\n", json_object_to_json_string(jso)); // displays 123.46
>> ...
> That's one possibility that I had considered. But we would also need a
> user_data also passed to the serializer, for example to be able to control
> the precision instead of having it hard-coded in it. This is the GDAL use
> case actually. The OGR GeoJSON driver has a user configurable option to
> specify the number of figures after decimal point.
Here's the API with that included:
int json_object_set_serializer(json_object *jso,
json_object_to_json_string_fn to_string_func,
void *userdata, // optional, can be NULL
void (*freeptr)(void *)); // optional, can be NULL even if
userdata is non-NULL
An example of the free function:
struct myinfo
{
int refcount;
...other fields...
};
void myfreefunc(json_object *jso, void *userdata)
{
struct myinfo *info = userdata;
info->refcount--;
if (info->refcount <= 0)
free(info);
}
> So in this approach the json_object structure would need 2 new fields, the
> pointer to the serializer func and the user_data (we would perhaps even need
> a pointer to a free function for the user data, but that's not strictly
> needed: we can assume that the caller is reponsible to free the user_data it
> provides to libjson, if needed).
Actually, we already have a field for the serializer function, so we
just need fields for the userdata and the free/delete function. I'm
adding that now.
> By the way, in the above serializer, the printbuf.h header should be used by
> user code. Is it indented to be used outside of libjson-c ?
I think that we would just declare it "quasi-public", and available
for use by custom serializer functions. I was thinking about renaming
it to json_printbuf, but since I don't see any other usages of
"printbuf" besides the one that comes with json-c, I'm just going to
leave it as-is.
eric