简体   繁体   English

SmartFormat 序列化字典的最佳方式

[英]SmartFormat best way to serialize a dictionary

I have a data object with an dictionary.我有一个带有字典的数据 object。 Now I want to serialize this dictionary to a json string.现在我想将此字典序列化为 json 字符串。 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;
}

Sure you could do that, but not in a generic way.当然你可以这样做,但不能以通用的方式。 SmartFormat is a formatter, rather than a serializer. SmartFormat是一个格式化程序,而不是一个序列化程序。 So in general, SmartFormat is best in filling a text template with data, like it is required with mail merge.所以一般来说, SmartFormat最适合用数据填充文本模板,就像邮件合并所需要的一样。

In your case, you'll be better off using serializers like System.Text.Json or Newtonsoft.Json.在您的情况下,最好使用 System.Text.Json 或 Newtonsoft.Json 等序列化程序。 For the latter, here is an example how simple this works: https://www.newtonsoft.com/json/help/html/serializedictionary.htm对于后者,这是一个简单的例子: https ://www.newtonsoft.com/json/help/html/serializedictionary.htm

I have attached my solution.我附上了我的解决方案。 You have to register the ToJSONFormatter with the AddExtensions Method.您必须使用 AddExtensions 方法注册 ToJSONFormatter。 After that you can call it like this: {MyVariable:ToJSON()}之后你可以这样调用它:{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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM