【问题标题】:newtonsoft json.net skip string or integersnewtonsoft json.net 跳过字符串或整数
【发布时间】:2013-03-16 13:34:19
【问题描述】:

我这里有点问题, 我想序列化一个字典,它包含string,integers,object

现在我正在遍历字典

 var data ="";
 foreach (var dict in dictObject)
 {
    var value = JsonConvert.SerializeObject(dict.value, Formatting.Indented,new JsonSerializerSettings()
     {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Converters = new List<JsonConverter>
                    {
                      new IsoDateTimeConverter(){DateTimeFormat = "yyyy-MM-dd hh:mm:ss"}    
                    }
      });

    data += dict.key +"="+ value;
 }

现在我不希望 Json.Net 序列化该字典中的 stringintegers 。因为很少有字符串包含\r\n,而且那里的事情变得一团糟。

所以我希望它跳过stringsintegers,但字典可能包含DateTime 等内容。我仅指出字符串和整数作为示例。

字典包含我自己的自定义类,entity classesintegersstringsdate time,等等等等。我只是想让JSON.NET 序列化我自己的自定义类和实体类。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# json serialization json.net


    【解决方案1】:

    您可以在序列化之前过滤您的字典,例如通过汇编:

    var customTypesAssembly = typeof(CustomClass).Assembly;
    var filteredDictionary = dictionary.Where(x => x.Value.GetType().Assembly == customTypesAssembly)
        .ToDictionary(x => x.Key, x => x.Value);
    
    var json = JsonConvert.SerializeObject(filteredDictionary);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      相关资源
      最近更新 更多