Skip to content

JSON merge patch may use BinaryData incorrectly #2771

@alzimmermsft

Description

@alzimmermsft

When using BinaryData with JSON merge patch it may be using it incorrectly. The following code is used:

String variableName = convenientParameterName + "InBinaryData";
javaBlock.line(String.format("JsonMergePatchHelper.get%1$sAccessor().prepareModelForJsonMergePatch(%2$s, true);", convenientParameterTypeName, convenientParameterName));
javaBlock.line(String.format("BinaryData %1$s = BinaryData.fromBytes(%2$s.toBytes());", variableName, expression)); // BinaryData.fromObject() will not fire serialization, use toBytes() to fire serialization
javaBlock.line(String.format("JsonMergePatchHelper.get%1$sAccessor().prepareModelForJsonMergePatch(%2$s, false);", convenientParameterTypeName, convenientParameterName));
return variableName;

https://github.com/Azure/autorest.java/blob/main/javagen/src/main/java/com/azure/autorest/template/ConvenienceMethodTemplateBase.java#L788

We should be using the BinaryData.fromObject directly rather than converting it from Object to byte[] then landing on BinaryData. This may also result in BinaryData being used incorrectly later on as it loses type information and may result it being considered binary in JSON (base64 encoded string) rather than a JSON object.

Edit

After further investigation I've realized it is done this way as BinaryData.fromObject doesn't serialize the object until the BinaryData is queried. And serialization needs to be forced as the patch serialization status is only within this block of code. This should still on use BinaryData.fromObject but the created BinaryData should have something like getLength() called which will force serialization.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions