Skip to content

Instantly share code, notes, and snippets.

@tombatron
Created September 1, 2021 22:43
Show Gist options
  • Save tombatron/85b1a862e3b136418d312440bc98b19c to your computer and use it in GitHub Desktop.
Save tombatron/85b1a862e3b136418d312440bc98b19c to your computer and use it in GitHub Desktop.
Example of writing a JSON object and then updating a property via its JSONPath with a filter...
using System;
using System.Text.Json;
using System.Threading.Tasks;
using NReJSON;
using StackExchange.Redis;
namespace RedisJsonTest
{
class Program
{
static async Task Main(string[] args)
{
var muxr = await ConnectionMultiplexer.ConnectAsync("localhost");
var db = muxr.GetDatabase(0);
NReJSONSerializer.SerializerProxy = new JsonSerializerProxy();
var result = await db.JsonSetAsync("example_json_key",
new ExampleWrapper(
new Example[]
{
new(1, "Test 1"),
new(2, "Test 2")
}), "$");
Console.WriteLine($"Write is successful? {result.IsSuccess}");
var initialResult = await db.JsonGetAsync("example_json_key", "$.List[?(@.Id == 2)].N");
Console.WriteLine(initialResult.ToString());
var updateResult = await db.JsonSetAsync("example_json_key", "\"Updated Value\"", "$.List[?(@.Id == 2)].N");
Console.WriteLine($"Update is successful? {updateResult.IsSuccess}");
var finalResult = await db.JsonGetAsync("example_json_key");
Console.WriteLine($"Final result: {finalResult}");
}
}
record Example(int Id, string N);
record ExampleWrapper(Example[] List);
class JsonSerializerProxy : ISerializerProxy
{
public TResult Deserialize<TResult>(RedisResult serializedValue) =>
JsonSerializer.Deserialize<TResult>(serializedValue.ToString());
public string Serialize<TObjectType>(TObjectType obj) =>
JsonSerializer.Serialize(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment