SmartFormat best way to serialize a dictionary

Viewed 34

I have a data object with an dictionary. Now I want to serialize this dictionary to a json string. Is it possible to do this inside the template?

public string GenerateTest()
{

    Dictionary<string, object> dataDictionary = new Dictionary<string, object>();

    dataDictionary.Add("Testdata1", "Value1");
    dataDictionary.Add("Testdata2", "Value2");

    

    string result = Smart.Format(CultureInfo.InvariantCulture, "{data.someFormattertoGetAnJsonString}", new {data= dataDictionary });
    Console.WriteLine(result);
    return result;
}
2 Answers

Sure you could do that, but not in a generic way. SmartFormat is a formatter, rather than a serializer. So in general, SmartFormat is best in filling a text template with data, like it is required with mail merge.

In your case, you'll be better off using serializers like System.Text.Json or Newtonsoft.Json. For the latter, here is an example how simple this works: https://www.newtonsoft.com/json/help/html/serializedictionary.htm

I have attached my solution. You have to register the ToJSONFormatter with the AddExtensions Method. After that you can call it like this: {MyVariable:ToJSON()}

Smart.Default.AddExtensions(new ToJSONFormatter());
        
public class ToJSONFormatter : IFormatter
{
    public string Name { get; set; } = "ToJSON";
    public bool CanAutoDetect { get; set; } = false;
    private JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ss" };

    //{Data:ToJSON()}
    public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
    {
        formattingInfo.Write(JsonConvert.SerializeObject(formattingInfo.CurrentValue));
        return true;
    }
}
Related