Skip to content

Commit 4de0e41

Browse files
authored
Update the JSON merge patch example (#3633)
Relates to Azure/typespec-rust#78
1 parent 10184e8 commit 4de0e41

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

sdk/core/azure_core/examples/core_json_merge_patch.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,16 @@
44
use azure_core::{http::Transport, Value};
55
use example::{setup, ExampleClient, ExampleClientOptions};
66

7-
/// This example demonstrates deserializing a standard Azure error response to get more details.
7+
/// This sample demonstrates how to update a resource and send it back in a [JSON merge patch](https://www.rfc-editor.org/rfc/rfc7396).
8+
///
9+
/// Basically,
10+
///
11+
/// * Property values are updated to new values in the request body.
12+
/// * Property values set to an explicit `null` are deleted or unset.
13+
/// * Missing properties are not changed.
14+
/// * Arrays are replaced entirely by the contents of the array in the request body.
15+
///
16+
/// You can deserialize a response payload into a [`Value`] and change values or even set to an explicit [`Value::Null`] as shown below.
817
async fn example_json_merge_patch() -> Result<(), Box<dyn std::error::Error>> {
918
let mut options = ExampleClientOptions::default();
1019

@@ -22,6 +31,7 @@ async fn example_json_merge_patch() -> Result<(), Box<dyn std::error::Error>> {
2231

2332
// Change the description and update tags.
2433
resource["description"] = "an updated foo".into();
34+
resource["optional"] = Value::Null;
2535
if let Some(tags) = resource["tags"].as_object_mut() {
2636
tags["test"] = true.into();
2737
tags.insert("version".into(), 1.into());
@@ -35,6 +45,7 @@ async fn example_json_merge_patch() -> Result<(), Box<dyn std::error::Error>> {
3545

3646
assert_eq!(resource.id.as_deref(), Some("foo"));
3747
assert_eq!(resource.description.as_deref(), Some("an updated foo"));
48+
assert_eq!(resource.optional, None);
3849

3950
let tags = resource.tags.expect("expected tags");
4051
assert_eq!(tags["test"], Value::Bool(true));
@@ -75,6 +86,7 @@ mod example {
7586
let mut resource = json!({
7687
"id": "foo",
7788
"description": "just a foo",
89+
"optional": "set",
7890
"tags": {
7991
"test": false
8092
}
@@ -137,6 +149,8 @@ mod example {
137149
pub struct Resource {
138150
pub id: Option<String>,
139151
pub description: Option<String>,
152+
// We want to serialize an explicit null.
153+
pub optional: Option<String>,
140154
#[serde(skip_serializing_if = "Option::is_none")]
141155
pub tags: Option<HashMap<String, Value>>,
142156
}

0 commit comments

Comments
 (0)