1

I have:

1)

Dictionary<MyClass, double>

2) elasticsearch 7

3) nest 7

I want to write my dictionary in elasticsearch database by:

client.IndexDocument(myDictionary).

I know, I can use

List<KeyValuePair<MyClass, double>>

But in my work I need use Dictionary.

Alexander
  • 23
  • 5
  • 2
    A dictionary *is* an IEnumerable. It should be no different than what you already have. Have you tried something, did you get an error? What do you mean `elasicsearch json` ? JSON is just one standard, there are no variations by product – Panagiotis Kanavos Dec 09 '19 at 12:47
  • Are you trying to serialize your data as an *array* instead of a single object? Or index multiple documents instead of a single one? In JavaScript/JSON, an object *is* a dictionary. If you want the result to be serialized as an array, don't use a `Dictionary<>` directly. Perhaps you can cast the dictionary to `IEnumerable>` and pass it to `IndexDocument`. If the client uses reflection though, it could still serialize it as an object. In that case you could use `ToArray()` or `ToList()` to convert the dictionary to a list – Panagiotis Kanavos Dec 09 '19 at 12:50
  • A dictionary in json has to be `string -> value`, where `value` can be any legal json construct, literal values, objects, lists. The key, however, has to be a string. So you will have to turn your `MyClass` objects into strings in order to serialize them as keys for a dictionary. Are you trying to produce json that fits a particular schema? is that why you're mentioning elastisearch or nest? – Lasse V. Karlsen Dec 09 '19 at 13:23

1 Answers1

0

You need to implement a type converter eg.MyClassConverter for MyClass and then add the attribute [TypeConverter(typeof(MyClassConverter))] to the MyClass class declaration. This means that, instead of using the default ToString(), it will use the type convert that you define to serialize as you want.

The link "How to: Implement a Type Converter" shows how to create a type converter.

The SO link showing the answer is: Not ableTo Serialize Dictionary with Complex key using Json.net

JerryTheGreek
  • 160
  • 2
  • 7