我使用VS 2012,.NET 3.5,JSON.NET
我有几个单值,如int,string types
我用~ separator
设置了字符串值。
我序列化字符串,将其保存在文件中
然后,我从文件中反序列化字符串,然后我拆分字符串。
我希望避免使用~ character
拆分,我希望避免创建一个新类型(具有属性get; set的类实体)。
我认为使用匿名类型或动态是复杂的。
有什么建议吗?
现在单元测试工作:
var value1 = "C20100101_0001";
var value2 = 678901;
var value3 = "lorem ipsum text %&/() more test";
var value4 = "email@gmail.com";
string json = "{0}~{1}~{2}~{3}".FormatString(value1, value2, value3, value4);
var ser = JsonConvert.SerializeObject(json);
ser = JsonConvert.SerializeObject(json, Formatting.Indented);
System.IO.File.WriteAllText(@".\path.txt", ser);
var deser = System.IO.File.ReadAllText(@".\path.txt");
var json2 = JsonConvert.DeserializeObject<string>(deser);
Assert.AreEqual(json, json2);
var data = json2.Split(new char[] { '~' });
Assert.IsNotNull(data);
Assert.AreNotEqual(0, data.Length);
Assert.AreEqual(value1, data[0]);
答案 0 :(得分:2)
据我了解,您可以将所有内容转储到数组中并序列化:
var list = new object[]{"C20100101_0001", 678901, "lorem ipsum text %&/() more test", "email@gmail.com"};
var json = JsonConvert.SerializeObject(list);
var deserialized = JsonConvert.DeserializeObject<object[]>(json);
答案 1 :(得分:1)
使用@EagleEak回答https://stackoverflow.com/a/28325833/206730,单元测试工作的解决方案:
var value1 = "C20100101_0001";
var value2 = 678901;
var value3 = "lorem ipsum text %&/() more test";
var value4 = "email@gmail.com";
var list = new object[] { value1, value2, value3, value4 };
ser = JsonConvert.SerializeObject(list, Formatting.Indented);
System.IO.File.WriteAllText(@".\path.txt", ser);
deser = System.IO.File.ReadAllText(@".\path.txt");
var deserialized = JsonConvert.DeserializeObject<object[]>(deser);
Assert.IsNotNull(deserialized);
Assert.AreNotEqual(0, deserialized.Length);
Assert.AreEqual(value1, deserialized[0]);