-1

I'm starting using C# and have a lot to learn.

I'm trying to create a JSON file with a dictionary (thats easy).

JsonSerializer.Serialize(MyDictionary)

But it returns the data without descriptions...

{
               "-0255504",
               "1"
            },
            {
               :"08000301",
               :"1"
            }

I want to to include some descriptions like:

{
               "ArticleId":"-0255504",
               "OrderedQuantity":"1"
            },
            {
               "ArticleId":"08000301",
               "OrderedQuantity":"1"
            },
            {
               "ArticleId":"03820235",
               "OrderedQuantity":"1"
            }

For sure is easy to include and don't want to use List for my program.

Is available any method or property to modify the format?

I'm Using System.Text.Json;

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 2
    Please provide us with a [mcve]. –  Mar 15 '21 at 18:15
  • 1
    The first JSON sample shown in your question is not well-formed. Upload it to https://jsonlint.com/ and you will get *`Error: Parse error on line 2:`*. Can you share a [mcve] showing how you generated that JSON? I am surprised that [tag:system.text.json] would generate such malformed JSON. We can't really tell you how to generate well-formed JSON with the required properties without knowing what you are doing currently that is not working. See: [ask]. – dbc Mar 15 '21 at 18:15
  • This is the result of the Json: – Hernán Avila Fernandez Mar 15 '21 at 18:51

1 Answers1

0

You can project your dictionary items into anonymous (or not anonymous) types to get your property names:

  Dictionary<string, string> d = new Dictionary<string, string>
            {
                { "-0255504", "1" },
                { "-08000301", "1" },
            };

  string json = JsonSerializer.Serialize(d.Select(entry => new { ArticleId = entry.Key, OrderedQuantity = entry.Value }));
Crowcoder
  • 11,250
  • 3
  • 36
  • 45