Cross-platform C SDK logo

Cross-platform C SDK

JSON

❮ Back
Next ❯
This page has been automatically translated using the Google Translate API services. We are working on improving texts. Thank you for your understanding and patience.

Functions

type*json_read (...)
voidjson_write (...)
voidjson_destroy (...)
voidjson_destopt (...)

JSON JavaScript Object Notation, is a data format in text mode that allows to easily represent basic types, objects and arrays. Although its use has become popular in the Web environment, it can also be used for other purposes, such as configuration files or local exchange. Its syntax is easy to understand for humans and simple to process for machines. In (Listing 1) we reproduce a small fragment of the JSON response of an example Web Service:

Listing 1: JSON fragment returned by a Web Service.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
    "code":0,
    "size":80,
    "data":[
    {"id":0,
    "code":"i7-8700K",
    "description":"Intel BX80684I78700K 8th Gen Core i7-8700K Processor",
    type":0,
    "price":374.8899999999999863575794734060764312744140625,
    "image":"cpu_00.jpg",
    "image64":"\/9j\/4AAQSkZJRgABAQ....
    },
    ...
    ]
}

In its structure we can find these data types:

  • Booleans: Represented by constants true or false.
  • Numbers: Use the exponential notation of C for floating-point values: 2.3, .76, -0.54 or 5.6e12 they are valid examples of numerical values. JSON does not distinguish between integers, negatives or reals.
  • Strings: Any text in quotes is considered a string. Supports any Unicode character in UTF-8 or through the escape sequence \uXXXXto indicate the codepoint.
  • Objects: They are delimited by keys and composed of several fields separated by commas. Each field is formed by an identifier (string) followed by a colon and a value that can be any simple type, object or array (Listing 2).
  • Listing 2: JSON object
    1
    2
    3
    4
    5
    6
    7
    
    {
        "field1" : true,
        "field2" : 24.67,
        "field3" : "Hello Pibe",
        "field4" : [1, 2, 4, 8.4],
        "field5" : { "x" : 34.32, "y" : -6.19 }
    }
    
  • Arrays: Lists of items delimited by brackets [...] and separated by commas. The values do not have to be the same type as usually happens in some programming languages (Listing 3).
  • Listing 3: JSON array
    1
    2
    3
    
    [
        18, "Hello Pibe", true, { "x" : 34.32, "y" : -6.19 }
    ]
    
  • null: Indicates the absence of value.
  • Binaries: JSON does not support binary data so opaque objects (images, for example) must be encoded in text and transmitted as a string type value. The most widespread and globally supported format is the Base64 where each character represents 6 bits of information.
NAppGUI's JSON parser automatically transforms Image objects to Base64 and viceversa, allowing images to be embedded as data fields.

1. Get JSON data

The first thing we must do is connect to the Web service using HTTP to perform the query and obtain the response JSON (Listing 4). We can also read the content of a JSON from a local file or any other data source.

Listing 4: Get a JSON stream from a web service or from disk.
1
2
Stream *stm = http_dget("http://serv.nappgui.com/dproducts.php", NULL, NULL);
Stream *stm = hfile_stream("/home/fran/appdata/config.json", NULL);

2. Convert JSON to objects

If everything went well, we will have in Stream * stm a block of text in JSON format. The next step will be to "parse" it to convert the character sequence into binary objects for use from the application (Listing 5).

Listing 5: Translate a JSON to a C object.
1
2
PJson *json = json_read(stm, NULL, PJson);
stm_close(&stm);

For this call to be successful, we have previously had to create the equivalent structures and register them in the internal application database (Listing 6). See Data binding to learn more about automatic data binding.

Listing 6: C structures that will house the content of the JSON.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
typedef struct _product_t Product;
typedef struct _pjson_t PJson;

struct _product_t
{
    uint32_t type;
    String *code;
    String *description;
    Image *image64;
    real32_t price;
};

struct _pjson_t
{
    int32_t code;
    uint32_t size;
    ArrPt(Product) *data;
};

dbind(Product, uint32_t, type);
dbind(Product, String*, code);
dbind(Product, String*, description);
dbind(Product, Image*, image64);
dbind(Product, real32_t, price);
dbind(PJson, int32_t, code);
dbind(PJson, uint32_t, size);
dbind(PJson, ArrPt(Product)*, data);

3. Convert objects to JSON

The reverse process is also very easy to do thanks to DBind. Let's imagine that we have made changes to the PJson object from the previous section and we want to save a copy in JSON format (Listing 7).

Listing 7: Translate a C object to JSON.
1
2
3
4
5
6
7
PJson *json = ...;

Stream *stm = stm_to_file("/home/fran/appdata/config.json", NULL);
json_write(stm, json, NULL, PJson);

stm_close(&stm);
json_destroy(&json, PJson);

json_read ()

Processes a JSON script. Will transform JSON data into a binary object.

type*
json_read(Stream *stm,
          const JsonOpts *opts,
          type);
stm

Data entry in JSON format.

opts

Options.

type

Type of data.

Return

Result object.

Remarks

See Convert JSON to objects.


json_write ()

Save a binary object in JSON format.

void
json_write(Stream *stm,
           type *data,
           const JsonOpts *opts,
           type);
stm

Data output in JSON format.

data

Object.

opts

Options.

type

Type of data.

Remarks

See Convert objects to JSON.


json_destroy ()

Destroy a JSON object.

void
json_destroy(type **data,
             type);
data

Object.

type

Type of data.


json_destopt ()

Destroy a JSON object, if this is not NULL.

void
json_destopt(type **data,
             type);
data

Object.

type

Type of data.

❮ Back
Next ❯