1

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;
}
atheos
  • 21
  • 4

2 Answers2

1

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;
    }
}
atheos
  • 21
  • 4
0

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

axuno
  • 581
  • 4
  • 15
  • it's a honor to get a answer from the producer itself. Thank you for the suggestion. I'm already familiar with Newtonsoft.Json and use it alot. My target in this purpose is to do this in a gerneric way because i pass different objects to a template class. In some cases I want to display the data as CSV or JSON(maybe within a QRCode). Therefore it would be nice if I can assume this task in a gernic way to prevent to serialise all the objects before passing to smartformat. – atheos Jun 02 '22 at 06:18
  • May I'm able to extent a formatter like "ToUpper" to serialize it? – atheos Jun 02 '22 at 06:25
  • Indeed, In this case, the best way to go probably is a custom formatter extension. You'll find a sample in the [SmartFormat Wiki](https://github.com/axuno/SmartFormat/wiki/Creating-Your-Own-Extension). It's quite straight-forward. – axuno Jun 03 '22 at 16:36