-2

I have a simple json:

{
    "timestamp": "38519277!12/14/2018 08:35:17",
    "entity": "Account",
    "entity": "Contact",
    "entity": "Case"
}

That I need to add to Dictionary:

Dictionary<string, string> objects = new Dictionary<string, string>();

The key is entity and the value is always the same timestamp. I'm not sure how to proceed. This is something I have not done before. Can anyone advise?

sy-huss
  • 183
  • 2
  • 14
  • 3
    Possible duplicate of [How can I deserialize JSON to a simple Dictionary in ASP.NET?](https://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) – Erik Šťastný Dec 14 '18 at 15:07
  • 2
    This is not even a valid json. You have duplicate `entity` keys in it... – meJustAndrew Dec 14 '18 at 15:13
  • It should be: `{ "timestamp": "38519277!12/14/2018 08:35:17", "entity": ["Account", "Contact", "Case"] }` What you have now is not valid and cant be deserialized. – Magnus Dec 14 '18 at 15:16

3 Answers3

0

Here...

string json = @"{""timestamp"":""38519277!12/14/2018 08:35:17"",""entity"":""Account""}";

Dictionary<string, string> objects = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

for more details :

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

Fadly
  • 191
  • 10
0

if you would like to use dictionary, the only way is to give value part as object type or dynamic.

Dictionary<string, object> objects = new Dictionary<string, object>();

if you are going to use JsonConvert, then use this Example

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
0

Assuming that you have a class that looks like this:

class Test
{
    public string timestamp { get; set; }
    public List<string> entity { get; set; }
}

...and your json object that looks like this (because as pointed out in the comments, your current json object is not valid)

"{ \"timestamp\": \"38519277!12 / 14 / 2018 08:35:17\", \"entity\": [\"Account\", \"Contact\", \"Case\"] }"

After deserializing var obj = JsonConvert.DeserializeObject<Test>(json);

This is the line of code that you want:

Dictionary<string, string> objects = obj.entity.ToDictionary(x => x, x => obj.timestamp);
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76