If I have a JSON value with unknown layout I can deserialise it with serde_json
using serde_json::Value
:
#[derive(Deserialize)]
struct Foo {
unknown: serde_json::Value,
}
Similarly I can do the same with CBOR:
#[derive(Deserialize)]
struct Foo {
unknown: serde_cbor::Value,
}
But what if I want a single data structure that can be loaded from JSON or CBOR. I effectively want this:
enum UnknownValue {
Json(serde_json::Value),
Cbor(serde_cbor::Value),
}
#[derive(Deserialize)]
struct Foo {
unknown: UnknownValue,
}
Is there any way to do this so that I can deserialise JSON or CBOR into this struct?
Ok, I tried
serde(untagged)
, and it sort of works, except that it always results inUnknownValue::Json
, even if you deserialise using serde_cbor. I'm not sure how that works exactly:Prints
So I wondered if maybe it just works if you use
serde_json::Value
and forget the enum, and lo, it does! Using this instead gives exactly the same output:So this doesn't answer my actual question (e.g. if you want to get CBOR tags), but it does satisfy my use case. Probably also worth mentioning serde-value which seems designed for this sort of thing, though I haven't tried it.