'How to serialize parameter values as JSON property?
I need a JSON string that the JSON key is property value instead of the property name.
I have these classes:
public class Group
{
public int Id { get; set; } = 1;
public string Name { get; set; } = "Test Group";
public IEnumerable<Document> Documents { get; set; }
}
public class Document
{
public int Id { get; set; } = 1;
public int GroupId { get; set; } = 1;
public string Key { get; set; } = "Test Key";
public string Value { get; set; } = "Test Value";
public Group Group { get; set; }
}
And my result has to be like that:
{
"Test Group": {
"Test Key": "Test Value",
"Test 2 Key": "Test 2 Value"
},
"Group 2": {
"Key 2": "Value 2"
}
}
Solution 1:[1]
It looks like you want to map a list of Document's to the inner json nodes and map a list of Group's to the outer nodes. Both of these can be mapped to a Dictionary using ToDictionary().
Assuming you have an enumerable of groups: var groups = some IEnumerable<Group>, then the following code produces your desired result:
// use ToDictionary on the groups, and on the Documents
var groupDictionary = groups.ToDictionary(g => g.Name,
g => g.Documents.ToDictionary(d => d.Key, d => d.Value));
var result = JsonConvert.SerializeObject(groupDictionary, Formatting.Indented);
// output
{
"Test Group": {
"Test Key": "Test Value",
"Test Key 2": "Test 2 Value"
},
"Group 2": {
"Key 2": "Value 2"
}
}
Where I've used Newtonsoft.Json to serialize. If you're using System.Text.Json instead you can serialize using:
JsonSerializer.Serialize(groupDictionary, new JsonSerializerOptions { WriteIndented = true });
Try the demo online
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
