如何让一个类能够同时被DataContractJsonSerializer序列化成JSON,又能够通过IFormatter序列化到文件

zgke 2009-03-14 11:25:54
如何让一个类能够同时被DataContractJsonSerializer序列化成JSON,又能够通过IFormatter序列化到文件 [.NET技术][C#]
...全文
129 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zgke 2009-03-14
  • 打赏
  • 举报
回复
就2楼的意思..可能类里还有那些问题..我去找下..
liujiayu10 2009-03-14
  • 打赏
  • 举报
回复
直接不知,间接的话自己写个方法来格式化成JSON格式呗
wuyi8808 2009-03-14
  • 打赏
  • 举报
回复
up
stonehy520 2009-03-14
  • 打赏
  • 举报
回复
LZ的问题太难了,我不会,帮顶
blc2003 2009-03-14
  • 打赏
  • 举报
回复
帮忙顶了
cppfaq 2009-03-14
  • 打赏
  • 举报
回复
说句实在话没有看懂老大想问啥。散分?
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
Customer person = new Customer();
person.Name = "John Jones";
person.Entered = new DateTime(2007, 10, 10);

person.Addresses.Add(new Address());
person.Addresses.Add(new Address());

TestJson(person);
TestIFormatter(person);

Console.ReadLine();
}

private static void TestIFormatter(Customer person)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("testIFormatter", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, person);
stream.Close();

IFormatter formatter2 = new BinaryFormatter();
Stream stream2 = new FileStream("testIFormatter", FileMode.Open, FileAccess.Read, FileShare.Read);
Customer person2 = formatter2.Deserialize(stream2) as Customer;
Console.WriteLine(person2.Name);
}

private static void TestJson(Customer person)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof (Customer));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, person);

string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
Console.WriteLine(json);


// *** Start from scratch with deserialization
//ms = new FileStream(Server.MapPath("jsonoutput.txt"), FileMode.Open);
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));

ser = new DataContractJsonSerializer(typeof (Customer));
Customer person2 = ser.ReadObject(ms) as Customer;
ms.Close();

Console.WriteLine(person2.Name);
}

#region Nested type: Address

[Serializable]
public class Address
{
public string City = "Paia";
public string State = "HI";
public string Street = "32 Kaiea Place";
public string Zip = "96779";
}

#endregion

#region Nested type: Customer

[Serializable]
public class Customer
{
public List<Address> Addresses = new List<Address>();
public DateTime Entered = DateTime.Now;
public string Name = "John";
}

#endregion
}
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧