0

I am attempting to use the cJSON library, written by Dave Gamble, to read in the following JSON request:

       {"id":"8358441244995838759","jsonrpc":"2.0","method":"addext",
       "params":["<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
        <trunks id=\"0\"><end_ch>3</end_ch>
        <gateway>172.20.222.52</gateway>
        <interface_type>E231</interface_type>
        <name>Mumbai_Avaya</name>
        <start_ch>12</start_ch>
        <sub_type>E1PRI</sub_type></trunks>"]}

I am able to retrieve the "id" and "method" by using below code, but not able to retrieve or print the values inside "params" which is an XML string. I want to print whatever inside the "params".

 cJSON *cjson, *method_obj;
 char *methodname;
 char *params;

 cjson = cJSON_Parse(buf);

method_obj = cJSON_GetObjectItem(cjson, "method");
methodname = method_obj->valuestring;
printf("method name %s\n", methodname);

method_obj = cJSON_GetObjectItem(cjson, "id");
id = method_obj->valueint;
char *str = method_obj->valuestring;
printf("id %s\n", str);

method_obj = cJSON_GetObjectItem(cjson, "params");
params=method_obj->valuestring;
printf("Params [ ] %s\n", params);

Please provide any suggestion.

Thanks in Advance.

Sled
  • 18,541
  • 27
  • 119
  • 168
Neeraj
  • 13
  • 6

2 Answers2

0

Either change method_obj->valuestring to method_obj->child->valuestring (after checking that child != NULL), or have the service, that generates the JSON request, not use an array if none is needed.

a3f
  • 8,517
  • 1
  • 41
  • 46
  • a3f@ Thanks man, It is working you save my day. I was trying with method_obj->child. +1 for the answer. – Neeraj Jul 18 '16 at 06:47
0

params of field type is JSON Array.
use cJSON_GetArrayItem (and cJSON_GetArraySize) API like this:

method_obj = cJSON_GetObjectItem(cjson, "params");
int size = cJSON_GetArraySize(method_obj);
for(int i = 0; i < size; ++i){
    params = cJSON_GetArrayItem(method_obj, i)->valuestring;
    printf("Params [ ] %s\n", params);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70