以人类可读的文本格式序列化 [英] Serialize in a human readable text format

查看:129
本文介绍了以人类可读的文本格式序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 2.0(C#)中是否有一种像使用XmlSerializer那样以简单/可自定义的人类可读格式对对象进行序列化的方法,例如,它看起来像 PXLS 还是JSON?
另外,我知道XML是人类可读的,我正在寻找具有较少烦人的冗余性的东西,可以将这些结果输出给用户。

Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like PXLS or JSON? Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.

推荐答案

要在.NET中序列化为JSON,请执行以下操作:

To Serialize into JSON in .NET you do as follows:

public static string ToJson(IEnumerable collection)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());
            string json;
            using (MemoryStream m = new MemoryStream())
            {
                XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);
                ser.WriteObject(m, collection);
                writer.Flush();

                json = Encoding.Default.GetString(m.ToArray());
            }
            return json;
        }

集合项需要具有 DataContract属性,并且每个成员希望被序列化为JSON的用户必须具有 DataMember属性。

The collections item need to have the "DataContract" attribute, and each member you wish to be serialized into the JSON must have the "DataMember" attibute.

这可能仅适用于.NET 3.5。但是对于2.0也有同样简单的版本...

It's possible that this only works for .NET 3.5. But there is an equally simple version for 2.0 aswell...

这篇关于以人类可读的文本格式序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆