Reputation: 19571
Running this program..
using System;
using System.Text.Json;
using System.Collections.Generic;
namespace XmlConsoleApp
{
class Program
{
static void Main(string[] args)
{
CampaignAccountMap campaignAccountMap = new CampaignAccountMap();
CampaignAccountMapItem campaignAccountMapItem = new CampaignAccountMapItem();
campaignAccountMapItem.CampaignId = @"dfdf-fdfdd-fdfd-dfdfd-dfdfd";
campaignAccountMapItem.AccountIds.Add(1245345);
campaignAccountMapItem.AccountIds.Add(1345675);
campaignAccountMap.Campaigns.Add(campaignAccountMapItem);
string jsonString = JsonSerializer.Serialize<CampaignAccountMap>(campaignAccountMap);
Console.Write(jsonString);
}
}
}
class CampaignAccountMap
{
public List<CampaignAccountMapItem> Campaigns { get; set; }
public CampaignAccountMap()
{
Campaigns = new List<CampaignAccountMapItem>();
}
}
class CampaignAccountMapItem
{
public string CampaignId { get; set; }
public List<int> AccountIds { get; set; }
public CampaignAccountMapItem()
{
AccountIds = new List<int>();
}
}
Outputs this JSON:
{
"Campaigns": [
{
"CampaignId": "dfdf-fdfdd-fdfd-dfdfd-dfdfd",
"AccountIds": [
1245345,
1345675
]
}
]
}
How can I customize the serialized output such that it produces this output instead?
{
"dfdf-fdfdd-fdfd-dfdfd-dfdfd": [
1245345,
1345675
]
}
Changing the name of the properties in from the class to the JSON seems doable using sterilizing annotations and such but I cant find any examples where those names are dynamic, ie I need the keys in the JSON output to be the dynamic values from the CampaignId property in the class.
I'm also open to doing this without using classes if I need to.
Upvotes: 1
Views: 46
Reputation: 16711
The desired json format can be represented by Dictionary<string, List<int>>
.
So, you could add a ToDictionary
method to your class, something like this:
class CampaignAccountMapItem
{
public string CampaignId { get; set; }
public List<int> AccountIds { get; set; }
public CampaignAccountMapItem()
{
AccountIds = new List<int>();
}
public Dictionary<string, List<int>> ToDictionary()
{
return new Dictionary<string, List<int>> {{ CampaignId, AccountIds }};
}
}
And use it like:
string jsonString = JsonSerializer.Serialize(campaignAccountMapItem.ToDictionary());
Console.Write(jsonString);
Upvotes: 2
Reputation: 14846
One way is to just use a Dictionary
.
var dict = new Dictionary<string, List<int>>();
foreach (var item in campaignAccountMap.Campaigns)
{
dict[item.CampaignId] = item.AccountIds;
}
var jsonString = JsonSerializer.Serialize(dict);
Console.Write(jsonString);
Upvotes: 2