in iothub/device/iot-device-client/src/main/java/com/microsoft/azure/sdk/iot/device/twin/MethodParser.java [144:265]
public synchronized void fromJson(String json) throws IllegalArgumentException
{
if (json == null || json.isEmpty())
{
throw new IllegalArgumentException("Invalid json.");
}
JsonParser jsonParser = new JsonParser();
try
{
JsonElement jsonElement = jsonParser.parse(json);
if (jsonElement instanceof JsonPrimitive || jsonElement instanceof JsonArray)
{
/*
Basic JSON String or Array
Ex:
"this is payload."
1
true
2.0e10
2.6
*/
this.operation = Operation.payload;
this.payload = jsonElement;
}
else if (jsonElement instanceof JsonObject)
{
JsonObject jsonObject = (JsonObject) jsonElement;
JsonElement statusTagNode = jsonObject.get(STATUS_TAG);
JsonElement methodNameNode = jsonObject.get(METHOD_NAME_TAG);
if (methodNameNode == null)
{
if (statusTagNode == null)
{
/*
If the json contains any payload without `methodName` or `status` identification, the fromJson shall parse only the payload, and set the operation as `payload`.
Ex:
{
"input1": "someInput",
"input2": "anotherInput"
}
*/
operation = Operation.payload;
payload = jsonObject;
}
else
{
/*
If the json contains the `status` identification, the fromJson shall parse both status and payload, and set the operation as `response`.
Ex:
{
"status": 201,
"payload": {"AnyValidPayload" : "" }
}
*/
operation = Operation.response;
if (statusTagNode.isJsonPrimitive())
{
status = statusTagNode.getAsInt();
}
JsonElement payloadNode = jsonObject.get(PAYLOAD_TAG);
if (payloadNode != null)
{
payload = payloadNode;
}
}
}
else
{
if (statusTagNode == null)
{
/*
If the json contains the `methodName` identification, the fromJson shall parse the full method, and set the operation as `invoke`.
Ex:
{
"methodName": "reboot",
"responseTimeoutInSeconds": 200,
"connectTimeoutInSeconds": 5,
"payload":
{
"input1": "someInput",
"input2": "anotherInput"
}
}
*/
operation = Operation.invoke;
name = methodNameNode.getAsString();
JsonElement responseTimeoutNode = jsonObject.get(RESPONSE_TIMEOUT_IN_SECONDS_TAG);
if (responseTimeoutNode != null)
{
responseTimeout = responseTimeoutNode.getAsLong();
}
JsonElement connetionTimeoutNode = jsonObject.get(CONNECT_TIMEOUT_IN_SECONDS_TAG);
if (connetionTimeoutNode != null)
{
connectTimeout = connetionTimeoutNode.getAsLong();
}
JsonElement payloadNode = jsonObject.get(PAYLOAD_TAG);
if (payloadNode != null)
{
payload = payloadNode;
}
}
else
{
throw new IllegalArgumentException("Invoke method name and Status reported in the same json");
}
}
}
else
{
// JSON null, since string is not empty, it shouldn't reach here
throw new IllegalArgumentException("Invalid json.");
}
}
catch (Exception ex)
{
throw new IllegalArgumentException("Malformed json.", ex);
}
}