1

for a legacy system, I need to return an object than have inside it a key value than it's the date, and inside have a body, any idea how to get the job done?

I need to return this array

{
"sellerId":"157747190185796800",
 "data":
 { 
  "2020-08-25":{ "sales":195000,"comission":25350},
  "2020-08-26":{"sales":70500,"comission":9165},
  "2020-08-27":{ "sales":51000,"comission":6630}
 } 
}
   

I'm trying with a json result and it works, but there's a problem with the key value date

Edit: I'm trying to make the suggestion of an dictionary, but, I don't know what I'm doing bad in this case. i try as an object too and doesn't work.

    var lst = new List<Dictionary<string, JsonResult>>();

    foreach (var item in listToReturn)
    { 

        lst.Add(new Dictionary(item.DateFromStr, new JsonResult (new
        {
            sales = item.sales,
            comission = item.Comission,
        })));
         
    }
sgrysoft
  • 588
  • 7
  • 14
  • 2
    Maybe you can consider to use `Dictionary` to data. – vernou Mar 24 '21 at 13:45
  • Please fix the indentation in the second code snippet. It is unreadable. – srk Mar 24 '21 at 13:56
  • when property name are value like int or datetime. It a hint that it's a dictionary. But why everything is a annomimous type? Is DTO for json such a burden ? You can creat them with a simple copy past. – Self Mar 24 '21 at 13:57
  • Does this answer your question? [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-string). Pasting the expected result into a tool https://app.quicktype.io will generate the class. And `.ToString("yyyy-MM-dd")` will be needed to convert a datetime to this format. – Self Mar 24 '21 at 14:09
  • 1
    Em... No, the format string it's not a problem... The date comes in a string with the correct format, the problem is how to show the value and from that value create a body with normal json – sgrysoft Mar 24 '21 at 16:28

1 Answers1

2

I would create the JSON using anonymous objects, using a Dictionary for the sales data like this:

var resultToReturn = new 
{
    sellerId,
    data = listToReturn.ToDictionary (
        item => item.DateFromStr,
        item => new 
        { 
            sales = item.Sales, 
            commission = item.Commission 
        }
    )
};

Then you can serialize resultToReturn using your favorite serializer, or if you're using MVC, return it in a JsonResult.

Demo fiddle: https://dotnetfiddle.net/jZvoNo

Note: this solution assumes all the date values will be unique within the list, otherwise ToDictionary will throw an exception.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300