I am using cjson library to create json and send it to server. I am using following code
char *string = cJSON_Print(json);
For which I get following output
{
"type1": "car",
"type2": "bus",
}
But the server expects it in string format like this
"{\n\t\"type1\":\t\"car\",\n\t\"type2\":\t\"bus\"\n}"
I am confused how can I achieve such conversion?
Related
I'm getting started with the Azure IoT SDK C-Library by using the IoT_Hub Device Method samples.
Does anybody know if the SDK provides a function to deserialize the JSON message payload? There are some good examples for payload serialization to JSON, but I wasn't able to find the counterpart.
I'm quite sure the SDK has some functionalities for JSON deserialization, e.g. something like:
BEGIN_NAMESPACE(WeatherStation);
DECLARE_MODEL(ContosoAnemometer,
WITH_DATA(ascii_char_ptr, DeviceId),
WITH_DATA(int, WindSpeed),
WITH_DATA(float, Temperature),
WITH_DATA(float, Humidity),
WITH_ACTION(TurnFanOn)
);
END_NAMESPACE(WeatherStation);
static int DeviceMethodCallback(const char* method_name, const unsigned char* payload, ...)
{
(void)userContextCallback;
ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
DESERIALIZE(myWeather, payload)
printf("Device Id: %i\r\n", myWeather->DeviceId);
// etc. etc.
}
In the Azure IoT SDK for C,it uses serializer library to serialize messages to send, but there is no couterpart(DESERIALIZE) for receiving messages.Please see
more about serializer. In serializer component, you will find jsondecoder.c, it defines some method for decode json data.
And more, you will find the parson component. It can be used to deserialize the object from json string.You can refer to the following code.
jsonstr
{"desString":"P7svG%2BLoUZEbB8Le5jP1%2BpuX2OVWLE4xWMzFcYFCRvNvDlcFVm%2B8z2VFO%2F%2BaEB8UAMa%2FZ0GGhooGNMWFE98Zmw%3D%3D","caller":{"mobile":"13996130361"},"accountId":"b5091dc91d700c6bf714e5fc446797d3","tmpTime":1428545890,"otherParam":"{id:12}","participant":[{"mobile":"18623582801"}],"servletUrl":"http://192.168.1.1:8090/xdr"}
C Code
JSON_Value *root_value=NULL;
root_value = json_parse_string(jsonstr);
JSON_Object *root_object;
if(json_value_get_type(root_value) == JSONObject)
{
root_object = json_value_get_object(root_value);
const char *desString = json_object_get_string(root_object, "desString");
if(desString!=NULL)strncpy(pPost->desString,desString,LENGTH128-1);
const char *accountId = json_object_get_string(root_object, "accountId");
if(accountId!=NULL)strncpy(pPost->accountId,accountId,LENGTH32);
double tmpTime = json_object_get_number(root_object, "tmpTime");
const char *caller = json_object_dotget_string(root_object,"caller.mobile");
if(caller!=NULL)strncpy(pPost->caller,caller,LENGTH16-1);
const char *servletUrl = json_object_dotget_string(root_object,"servletUrl");
if(servletUrl!=NULL)strncpy(pPost->servletUrl,servletUrl,LENGTH128-1);
const char *otherParam = json_object_dotget_string(root_object,"otherParam");
if(otherParam!=NULL)strncpy(pPost->otherParam,otherParam,LENGTH128-1);
JSON_Array *array;
array = json_object_get_array(root_object, "participant");
int i =0;
for(i;i<json_array_get_count(array);i++)
{
JSON_Object *tmp = json_array_get_object(array,i);
if(tmp!=NULL)
{
const char *mobile = json_object_get_string(tmp,"mobile");
if(mobile!=NULL)strncpy(pPost->callee,mobile,LENGTH16-1);
}
}
}
if(root_value)json_value_free(root_value);
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.
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.
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);
}
I tried to encode a byte array using glib2.0. After I add the encoded data to a json object, after I send the encoded data through pubnub client,
I got doble slashed string from json.
This is my code :
//code for encoding data
const guchar *data=inputEncodingData;
encodedData=g_base64_encode (data,datalength);
g_print("Encoded data==>%s\n",encodedData);
It produces encoded string with slashes. like this
KA4IChkAGQAAAAAAAAAAAOAO4A4uDgAAAAAAAAoAGAAmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQD//wAAwf/A/8D/AAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAEA//8CAP7/BAD6/wgA9P8SAOb/JwA2/A39mP0AAAIA4P/wD939pf2w/eL87vxz
/Nn7zasAAHMKAADIlAkKGAAYAAAAAAAAAAAA4Jbgls6UAAAAAAAACgAYACYAAAAAAAAAyf+9/7//
vv/B/8D/wP+8/77/v//C/8D/vf+//8D/wP++/77/
This is the code for creating json object:
struct json_object *obj1;
obj1 = json_object_new_object();
json_object_object_add(obj1, "result", json_object_new_string(encodedData));
This will print like this:
KA4IChkAGQAAAAAAAAAAAOAO4A4uDgAAAAAAAAoAGAAmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQD\/\/wAAwf\/A\/8D\/AAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAEA\/\/8CAP7\/BAD6\/wgA9P8SAOb\/JwA2\/A39mP0AAAIA4P\/wD939
pf2w\/eL87vxz\/Nn7zasAAHMKAADIlAkKGAAYAAAAAAAAAAAA4Jbgls6UAAAAAAAACgAYACYAAA
AAAAAAyf+9\/7\/\/vv\/B\/8D\/wP+8\/77\/v\/\/C\/8D\/vf+\/\/8D\/wP++\/77\/
Why is it like this? Any idea? I need data with one slash.
I like to unmarshal a JSON string using Decode():
var message Message
decoder := json.NewDecoder(s)
err = decoder.Decode(&message)
My data structure is
type Message map[string]interface{}
The test data is as follows:
{
"names": [
"HINDERNIS",
"TROCKNET",
"UMGEBENDEN"
],
"id":1189,
"command":"checkNames"
}
It's working fine for numbers and strings, but with the string array I get following panic:
panic: interface conversion: interface is []interface {}, not []string
this is not possible by conversion because a slice of struct != slice of interface it implements!
either you can get the elements one by one and put them into a []string like this: http://play.golang.org/p/1yqScF9yVX
or better, use the capabilities of the json package to unpack the data in your model format : http://golang.org/pkg/encoding/json/#example_Unmarshal
First off, this is a very broad question, and it might come across as me asking for the community to write my code for me. That is not my intent, but I am so lost, I don't know how to give enough information.
I am attempting to use the cJSON library, written by Dave Gamble,
I found this is very useful to use for my embedded device for JSON parse and composing.
to read in the following JSON array
{
"name": "Jack",
"types":[23,56,78],
"format": {
"type": "rect",
"width": 1920, }
}
.. and parsing the getting the object worked with this method
cJSON *format = cJSON_GetObjectItem(json,"format");
int framerate = cJSON_GetObjectItem(format,"width")->valueint;
but I am not able to parse the key "name" and object simple key value ,
I tried this
cJSON *array = cJSON_GetArrayItem(json,"types");
int value = cJSON_GetArrayItem(format1,1)->valueint;
but did not work, how to parse the array object and simple key value..
Your json is just fine. You can iterate through array of values in cJSON:
cJSON * array = cJSON_GetObjectItem(json, "types");
for (i = 0 ; i < cJSON_GetArraySize(array) ; i++)
{
printf("%d ",cJSON_GetArrayItem(array, i)->valueint);
}
will print
23 56 78
I think JSON element should respect key:value format.
{
"name": "Jack",
"types":[{"type" : 23}, {"type" : 56}, {"type":78}],
"format": {
"type": "rect",
"width": 1920, }
}