-2

I have a .json file which I want to convert to a c# dictionary (string, string).

the JSON looks like:

[
    {
        "data": "data",
        "id": "1"
    },
    {
        "data": "data2",
        "id": "2"
    }
]

what is the simplest way to achieve it?

dbc
  • 104,963
  • 20
  • 228
  • 340
Shax
  • 7
  • 1

1 Answers1

0

The JSON in your question is an array of objects containing two properties corresponding to keys and values, and you would like to map that to a Dictionary<string, string> containing those keys and values, e.g. {"data":"1","data2":"2"} or {"1":"data","2":"data2"} (your question isn't clear which you want).

To do that, first introduce a DTO corresponding to the JSON objects in your array:

record DataItemDTO(string data, string id);

But in versions of c# earlier than c# 9 / .NET 5, as mentioned by @flydog57 instead define:

public class DataItemDTO { public string data {get; set;} public string id {get; set;} }

And now you can do:

await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true);
var list = await JsonSerializer.DeserializeAsync<List<DataItemDTO>>(stream);
var dictionary = list?.ToDictionary(d => d.data, d => d.id);

Demo fiddle #1 here.

Or, if you want the "id" property to be used as the dictionary key, do:

var dictionary = list?.ToDictionary(d => d.id, d => d.data);

Demo fiddle #2 here.

If you would prefer to use synchronous IO, do:

using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
var list = JsonSerializer.Deserialize<List<DataItemDTO>>(stream);

Demo fiddle #3 here.

Notes:

  • Here path is a c# string containing the path to your JSON file on disk. In your comment you mentioned you tried File.ReadAllText(@"PATH") but this code likely failed because it attempted to read a file named PATH not a file located at some specified path.

  • If your array of JSON objects contains duplicate values for the dictionary key property, e.g. if you want to use "data" as the key:

    [
        {
            "data": "data",
            "id": "1"
        },
        {
            "data": "data",
            "id": "2"
        }
    ]
    

    You will get a System.ArgumentException: An item with the same key has already been added constructing the dictionary.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    If you are not running a recent compiler (i.e., one that understands `record`), you can create a simple POCO class: `public class DataItemDto { public string data {get; set;} public string id {get; set;} }` – Flydog57 Jul 25 '22 at 18:52
  • @Flydog57 - correct, but most people using System.Text.Json are also using .NET 5 or later. – dbc Jul 25 '22 at 18:57