azure-iot-sdk-c 反序列化 JSON payload



我开始使用 Azure IoT SDK C-LIBRARY,方法是使用 IoT_Hub 设备方法示例。

有谁知道SDK是否提供了反序列化JSON消息有效负载的功能?有一些将有效负载序列化为 JSON 的好例子,但我找不到对应的示例。

我很确定SDK具有一些用于JSON反序列化的功能,例如:

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: %irn", myWeather->DeviceId);
// etc. etc.
}

在适用于 C 的 Azure IoT SDK 中,它使用序列化程序库来序列化要发送的消息,但没有用于接收消息的 couterpart(反序列化(。请看 有关序列化程序的更多信息。在序列化程序组件中,你会发现jsondecoder.c,它定义了一些解码json数据的方法。

此外,您将找到帕森组件。它可用于从 json 字符串反序列化对象。您可以参考以下代码。

杰森斯特

{"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 代码

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);

相关内容

最新更新