I have a list with each item as:
public class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
Imagine the list has two items like below (in fact it can have several items)
Item1 : Name=A / Value=1000
Item2 : Name=B / Value=2000
I want to have a JSON like this:
{
"Date":"2023-11-19",
"A":"1000",
"B":"2000"
}
3
Answers
You can use the
.ToDictionary()
to convert the list of objects into a key-value pair (Dictionary).Based on your output, unsure where is the
Date
comes from. If theDate
is not appeared in the list and you want it to be appeared in the key-value pair, you need to add theDate
.Please find the attached code below :
To convert a list of Item objects into a JSON format as specified, you can use LINQ and Newtonsoft.Json in C# to achieve this transformation.
Here’s an example:
This code first creates a list of Item objects. Then, it transforms this list into a dictionary where the Name property of each Item object becomes a key, and the Value property becomes the value in the dictionary. Additionally, it adds a "Date" key to the dictionary with the current date.
Finally, it converts the dictionary into a JSON string using Newtonsoft.Json’s SerializeObject method, resulting in the desired JSON format:
This output contains the "Date" key along with the keys/values from the Item objects in the desired format.