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,
        })));
         
    }
5
  • 2
    Maybe you can consider to use Dictionary to data. Commented Mar 24, 2021 at 13:45
  • Please fix the indentation in the second code snippet. It is unreadable. Commented Mar 24, 2021 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. Commented Mar 24, 2021 at 13:57
  • Does this answer your question? How to auto-generate a C# class file from a JSON string. Pasting the expected result into a tool app.quicktype.io will generate the class. And .ToString("yyyy-MM-dd") will be needed to convert a datetime to this format. Commented Mar 24, 2021 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 Commented Mar 24, 2021 at 16:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.