Introduction to JSON format parsing and Libjson (how to use Cjson) _c language

Source: Internet
Author: User

Before reading this article, please read the article "Rss Reader Instance development system design".

In the development of Rss reader instance, there are two kinds of data formats: JSON and XML, which are used in network data exchange. This article mainly introduces the simple concept of JSON format and the application of JSON in RSS reader, the use of XML format will be introduced in the next article.

Introduction to JSON:

JSON (JavaScript Object notation) is a lightweight data interchange format that allows you to understand the structure of JSON as a unordered, nested set of Key-value-key-value pairs that are organized in the form of a struct or array. The Key-value key-value pairs at the same level are separated by a "," (comma), and each Key-value key value pair is followed by a key with a ":" (colon) followed by the value of the key corresponding to the colon. Key is a word that consists of uppercase and lowercase letters, underscores, and numbers, can be enclosed in double quotes, or without double quotes, and value sets are: Number, Boolean (TRUE or false), NULL, String, object, and array. As shown in Figure I:

(Figure I)

1, Number: Numerical value, including plastic and floating points, such as: 123, 0.83, -2.7e10. Its structure is shown in Figure II:

(Figure II)

2, String: String, is a series of characters enclosed in double quotes, using backslashes to escape, such as: \ \ \ n, and so on, the concept of string in JSON is similar to C + + or the Java language string concept, such as: "ABC." Its structure is shown in Figure three:

(Figure III)

3, Object: Objects, can also be understood as a struct, is a pair of curly braces closed up the unordered Key-value key value pairs collection, for example: {name: "Susan", age:27, birthday:{year:1984, Month:2, day : 11}; can also be written as: {"name": "Susan", "Age": "Birthday": {"Year": 1984, "month": 2, "Day": 11}}; Its structure is as Figure four:

(Figure IV)

4, array: Array, JSON arrays are a collection of value enclosed in brackets, that is, the data types of each member within the array can be different, which is not the same as the C/java array concept. Each value is separated by a "," (comma), such as: [123, ABC, FALSE, {NAME:MJ}], and its structure is shown in Figure V:

(Figure V)


For more information on JSON and tutorials please go to the web to search, there are many.

Let's start by writing an example:

 {result:true, root:{version: "201007091640", channels:[{

        Name: "News Center", subchnls:[{title: "Focus News", Link: "Http://jb51.net/news/channel/1/news.rss", Desc: "Housework, the affairs of the World"}, {title: "News Channel", Link: "Http://jb51.net/news/channel/2/news.rss" , desc: "Let you grasp the international dynamics in real Time"}, {title: "Military Channel", Link: "Http://jb51.net/news/channel/3/news." RSS ", desc:" Military "}]}, {name:" Sports News ", subchnls:[{ti TLE: "Sports News Summary", Link: "Http://jb51.net/news/channel/4/news.rss", desc: "EREWR"}, {T

    

    Itle: "International football", Link: "Http://jb51.net/news/channel/5/news.rss", desc: "WEREWR"}]} ]

  }

}

This JSON describes an object (the part enclosing the outermost brace), which we call object A for convenience of distinction. Object A has two item (that is, the Key-value key value pair), one is result, its value is true, and one is root and its value is an object, called Object B. Object B also has two item, one is version, its value is a string "201007091640"; one is channels, the value is an array, and the member of the array is an object, and each object contains two item, one is name and the value is string " News Center "and" Sports News "; one is subchnls, values are arrays, each array has several members, each SUBCHNLS member is an object, and each object has three Item:title, link, and Desc. Maybe you see this, it's already a sweat, but that's okay, let's take a map of this JSON text, and there's the truth, see figure VI:

(Figure VI: Black solid lines are objects, dotted lines are values, orange solid lines are arrays)

Using Cjson in RssReader:


Use open Source Library Cjson to parse JSON in RssReader, so here's how to use Cjson:

In Cjson, a Key-value key value pair is parsed and stored in a cjson struct variable whose value set is: False,true,null,number,string,object,array. They are stored separately in the child, valuestring, Valueint, and valuedouble variables of the Cjson object, while the data type used to determine the value of a Cjson object is the type variable of the Cjson object. Its value range and Cjson object's value set is one by one corresponding, such as: Cjson_false corresponding to False.

Cjson Types:

#define   cjson_false   0

#define   cjson_true   1

#define   cjson_null 2

#define   Cjson_number  3

#define   cjson_string  4

#define   cjson_array   5

#define   Cjson_object  6

Cjson Structure Body:

typedef struct Cjson

{

  struct Cjson *next,*prev;  Point to the previous/next

  struct Cjson *child;  Point to the next level, that is, when type is Cjson_object or Cjson_array, this pointer is not empty.

  int type;          

  Char *valuestring; int Valueint When type is cjson_string

  ;    Double valuedouble when type is Cjson_number

  ///when type is Cjson_number

 

  char *string;    The name of the current item, which is the key of the Key-value key value pair

Cjson;

In parsing JSON, a mapping relationship between the value data described in JSON format and the variables stored in the Cjson object is shown in Figure VII:

(Figure Seven)

The parsing of the Cjson format is the use of the Cjson_parse () method, its incoming parameter is a cjson of the object/array structure of the string, the success of the resolution returns a Cjson structure variables of the pointer, after the completion of the use of the call to Cjson_delete () Destroy the pointer. Cjson is a tree structure to organize the internal Cjson structure variables, in general, to use a cjson struct variable, you need to call the Cjson_getobjectitem () method and based on its parent node Cjson structure variable pointer and the name of the item to get its pointer , give an example:

BOOL Bresult;

Char jsonstring[] = "{result:true}";

Gets the value of result true

cjson* pitem = NULL;

cjson* proot = Cjson_parse (jsonstring);

if (proot)

{

  pitem = Cjson_getobjectitem (proot, "result");

  if (Pitem)

  {

    bresult = pitem->valueint;  Because the value of result is type Cjson_false or cjson_true, its value is stored in the valueint variable

  }

  cjson_delete (proot);

In the example above, regardless of the type of the value type of result, the pointer to its corresponding Cjson struct variable is obtained by calling the Cjson_getobjectitem () method, but only when processing its corresponding value. If the value type of result is cjson_object, you need to get a pointer to its child item by calling Cjson_getobjectitem (Pitem, "Subitemkey"). When you work with the item with the value type Cjson_array, you need to use another two api:cjson_getarraysize () and Cjson_getarrayitem (). Let's cite an example of getting an array member value:

char* out;

Char jsonstring[] = "{colors:[\" red\ ", \" green\ ", \" blue\ ", \" yellow\ ", \" White\ "]}";

cjson* Parray = NULL;

cjson* proot = Cjson_parse (jsonstring);

if (proot)

{

  Parray = Cjson_getobjectitem (proot, "colors");

  if (Parray)

  {

    cjson* parrayitem = NULL;

    int ncount = cjson_getarraysize (Parray); Gets the size of the Parray array for

    (int i = 0; i < ncount i++)

    {

      Parrayitem = Cjson_getarrayitem (Parray, i);

      out = Cjson_print (Parrayitem);  The Parrayitem value is printed as a string onto the char buffer, and cjson_print () automatically allocates the memory space, and the memory needs to be freed.

      ss_printf ("Array Item%d:%s\n", I, out);

      Free (out);

    }

  Cjson_delete (Proot);

}

When extracting data in a complex JSON format, it is only a combination of the methods used by the above two examples. Therefore, the use of APIs provided by Cjson is very simple and effective. With the above knowledge, we can write some code to parse the JSON in example one and extract the data, or the paste point code is the hard truth, the code is as follows:

TCHANNELSDATA.H:

/** Information Structure Body * */struct Subchnl_data {subchnl_data ();

 

  void Clear ();

  Tuchar * M_TITLE;

  char * m_link;

Tuchar * M_DESC;

 

};

 

  /** Large Channel INFORMATION structure * * */struct Channel_data {channel_data ();

  tuchar* M_psztitle;

Vector m_asubchnllist;

 

};

....//Tchannelsdata class member variable: Rssreaderconfig version number char m_pszversion[32];;

Tchannelsdata class member variable: Channel information list vector m_achnlslist;

............. TChannelsData.cpp:/** parsing JSON-formatted content * * \param pszjsontext parsed JSON-formatted content String * * \return true: there are updated data;

  False: No update data/Boolean Tchannelsdata::P arsejson (char* pszjsontext) {//char* out;

 

  cjson* Objjson;

 

  objjson= Cjson_parse (Pszjsontext);

    if (Objjson) {//out=cjson_print (Objjson);

 

    cjson* Objrootitem = NULL;

    To determine whether the need to update Objrootitem = Cjson_getobjectitem (Objjson, "result");

      if (Objrootitem) {if (!objrootitem->valueint) {return FALSE;

    } else {return FALSE;

 
}
    Gets the update data, the root node root objrootitem = Cjson_getobjectitem (Objjson, "root");

 

      if (objrootitem) {cjson* objjsonitem = NULL;

      Gets the version number Objjsonitem = Cjson_getobjectitem (Objrootitem, "version");

        if (objjsonitem) {Int32 Nlen = strlen (objjsonitem->valuestring);

      strncpy (M_pszversion, objjsonitem->valuestring, (Nlen <)? nlen:31);

    }//Parse out large channel _parsechannels (Objrootitem);

    }//ss_printf ("=======[parse json]%s\n", out);

    Cjson_delete (Objjson);

  Free (out);

return TRUE; 

/** parse out Large channel * * \param Pcjson Cjson Object pointer * * \return void/void Tchannelsdata::_parsechannels (cjson* pcjson)

 

  {cjson* Pjsonarray = NULL;

  if (!pcjson) {return;

  } Pjsonarray = Cjson_getobjectitem (Pcjson, "channels");

    if (Pjsonarray) {cjson* parrayitem = NULL;

 

    cjson* pjsontemp = NULL;

 Int32 nsize = cjson_getarraysize (Pjsonarray);   for (Int32 i = 0; i < nsize; i++) {Parrayitem = Cjson_getarrayitem (Pjsonarray, i);

        if (parrayitem) {Channel_data tchanneldata;

 

        Int32 nlen = 0;

        

        Get the large channel name tchanneldata.m_psztitle = _jsongettustring (Parrayitem, "name");

 

        The _parsesubchnls of the channel (Tchanneldata.m_asubchnllist, Parrayitem) is analyzed.

      Press the large channel information object into the list m_achnlslist.push_back (Tchanneldata);

      else {continue;

/** Parse Sub Channel * * \param asubchnllist Vector object that holds child channel data * \param Pcjson Cjson Object pointer * * \return void

 

  */void Tchannelsdata::_parsesubchnls (vector& asubchnllist, cjson* pcjson) {cjson* pjsonarray = NULL;

  if (!pcjson) {return;

  } Pjsonarray = Cjson_getobjectitem (Pcjson, "subchnls");

    if (Pjsonarray) {cjson* parrayitem = NULL;

 

    cjson* pjsontemp = NULL;

    Int32 nsize = cjson_getarraysize (Pjsonarray); FoR (Int32 i = 0; i < nsize; i++) {Parrayitem = Cjson_getarrayitem (Pjsonarray, i);

        if (parrayitem) {Subchnl_data tsubchnldata;

 

        Int32 nlen = 0;

 

        Get title Tsubchnldata.m_title = _jsongettustring (Parrayitem, "title");

 

        Get link Tsubchnldata.m_link = _jsongetstring (Parrayitem, "link");

 

        Get desc Tsubchnldata.m_desc = _jsongettustring (Parrayitem, "desc");

      Asubchnllist.push_back (Tsubchnldata); /** gets the specified property value of the specified Cjson object * * \param pjsonitem Cjson Object pointer * \param pszkey Cjson Object Properties * * \return return  The value of the JSON object, returned in Tuchar string/tuchar* tchannelsdata::_jsongettustring (cjson* pjsonitem, char* pszkey) {tuchar* PszValue

  = NULL;

  Int32 Nlen;

 

  cjson* pjsontemp = NULL;

  Pjsontemp = Cjson_getobjectitem (Pjsonitem, Pszkey);

    if (pjsontemp) {Nlen = strlen (pjsontemp->valuestring) + 1;

    Pszvalue = new Tuchar[nlen]; if (pszvalUE) {memset (pszvalue, 0, Nlen * sizeof (TUCHAR));

    Tustring::strutf8tostrunicode (Pszvalue, (const char*) pjsontemp->valuestring);

} return pszvalue; /** gets the specified property value of the specified Cjson object * * \param pjsonitem Cjson Object pointer * \param pszkey Cjson Object Properties * * \return Returns the value of the JSON object, in Char

  String form return * * * char* tchannelsdata::_jsongetstring (cjson* pjsonitem, char* pszkey) {char* = NULL;

  Int32 Nlen;

 

  cjson* pjsontemp = NULL;

  Pjsontemp = Cjson_getobjectitem (Pjsonitem, Pszkey);

    if (pjsontemp) {Nlen = strlen (pjsontemp->valuestring) + 1;

    Pszvalue = new Char[nlen];

      if (pszvalue) {memset (pszvalue, 0, Nlen);

    strncpy (Pszvalue, pjsontemp->valuestring, nLen-1);

} return pszvalue; /** gets the specified property value of the specified Cjson object * * \param pjsonitem Cjson Object pointer * \param pszkey Cjson Object Properties * * \return Returns the value of the JSON object to int32 Form return * * Int32 tchannelsdata::_jsongetint (cjson* pjsonitem, char* pszkey) {Int32 Nvalue = 0;

 

  cjson* pjsontemp = NULL;

  Pjsontemp = Cjson_getobjectitem (Pjsonitem, Pszkey);

  if (pjsontemp) {nvalue = pjsontemp->valueint;

return nvalue; /** gets the specified property value of the specified Cjson object * * \param pjsonitem Cjson Object pointer * \param pszkey Cjson Object Properties * * \return Returns the value of the JSON object to Boole

  An form returns */Boolean Tchannelsdata::_jsongetboolean (cjson* pjsonitem, char* pszkey) {Boolean bvalue = FALSE;

 

  cjson* pjsontemp = NULL;

  Pjsontemp = Cjson_getobjectitem (Pjsonitem, Pszkey);

    if (pjsontemp) {if (pjsontemp->valueint) {bvalue = TRUE;

} return bvalue; }

Summarize:

The structure of JSON is simple, so the amount of data in the JSON document is small, it is more suitable for the exchange of network data, and the method of parsing and extracting the JSON documents is simple, which is easy for the programmer to use, of course, because of the simplicity of the JSON structure, JSON is slightly less readable and editable than XML, so JSON is better suited to use during periods with fewer people reading and editing.

Note: The verified name should be added "such as char jsonstring[] =" {\ "result\": true} ";

The above is a small series for you to bring the JSON format parsing and Libjson usage introduction (about the use of Cjson) all content, I hope we support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.