0

The only experience I have with Json so far is for the most part the out-of-the-box wrappers, so please bear with me... So, I have a FlowDocument which has text. Inside the text words can be Hyperlinks. These Hyperlinks point to objects it represents. As a short example:

My dog is very sweet.

in this example dog is a hyperlink pointing to a Dog class with some basic fields, for instance:

name: Fido
owner: me
isGoodBoy: yes

behind the scenes this coupling is done through a Dictionairy<Hyperlink, Dog>

Now I want to serialize this construction without losing the hirarchy / references Since the document has references to the Dict, I need to serialize that first. When I perserve reference handling out of the box on this bird's eye view level I get:

{
    "$id": "1",
    {
        “dog” : { “name” : “Fido”,“owner”: “me”,“isGoodBoy”: “yes”},
    }
}

and: "$id": "2" on the SerializedFlowDocument

Serializing the document itself is not a problem as I don't need to serialize any mark-up, simplified, I can grab the string from each run and put them in an array. I'd end up with something like

serializedDoc[0] =“My ”
serializedDoc[1] =”dog”
serializedDoc[2] =“ is very sweet.”

However dog was a hyperlink, so I'd rather see serializedDoc[1] = "$ref": "1" Which brings me back to the Dict. Is there a way to specify that I want a reference to the Key in the k/v-pair instead of the whole Dict? Something in the lines of this:

{
    {
        “dog”
        "$id": "1": { “name” : “Fido”,“owner” : “me”,“isGoodBoy” : “yes”},
    }
}
NewInTown
  • 13
  • 4
  • 2
    None of this is valid JSON, it's unclear exactly what you want. Smart quotes `“”` definitely are not valid – Charlieface Feb 24 '21 at 18:43
  • TypeNameHandling or PreserveReferencesHandling only work for JSON objects and arrays, not primitives, so there's no built-in method to serialize a string primitive using the `"$id"` / `"$ref"` mechanism. But why do you need to do this for a string? Aren't you just going to look it up in the dictionary anyway? Can you [edit] your question to share a [mcve] with compilable classes, and well-formed JSON (no smart quotes please)? – dbc Feb 24 '21 at 18:57
  • Alternatively, if you have a dictionary with complex keys that can't be converted from and to a string, you can store the dictionary as an array, see [How can I serialize/deserialize a dictionary with custom keys using Json.Net?](https://stackoverflow.com/q/24681873) and also [this answer](https://stackoverflow.com/a/61549273) to [Not ableTo Serialize Dictionary with Complex key using Json.net](https://stackoverflow.com/q/24504245). Having done so I believe PreserveReferencesHandling will work on the keys, - though since `KeyValuePair` is an immutable struct that needs checking. – dbc Feb 24 '21 at 19:07

0 Answers0