问题描述
我已经找到了一些辅助方法,它让我的目的是JSONM和JSON转换成一个对象。现在,我读的,看起来像这样的JSON文件:
I have found some helper method that allow me to convert an object to JSONM and JSON to an object. Now I am reading in a json file that looks something like this:
/************************************************************************/
/* Coments Here *********************************************************/
/************************************************************************/
//more comments
[{
"Id": 1,
"Name": "HP Up"
},
{
"Id": 2,
"Name": "Regeneration"
}]
现在虽然我可以转换成JSON再presents 1对象,我会去有关与多个对象将这个C#.net 3.5?
Now while I can convert JSON the represents 1 object, I would I go about converting this in multiple objects with C# .NET 3.5?
推荐答案
您需要使用DataContractJsonSerializer这是在System.Runtime.Serialization.Json命名空间。标记您的类用[CollectionDataContract]属性的[DataContract]属性,集合类和属性与[数据成员]属性。
You need to use DataContractJsonSerializer which is in the System.Runtime.Serialization.Json namespace. Mark your class with the [DataContract] attribute, collection classes with the [CollectionDataContract] attribute and the properties with the [DataMember] attribute.
[CollectionDataContract]
public class People : List<Person>
{
}
[DataContract]
public class Person
{
public Person() { }
[DataMember]
public int Id{ get; set; }
[DataMember]
public string Name { get; set; }
}
下面是一个辅助类序列化(要)和反序列化(从)
Here is a helper class to serialize (To) and deserialize (From)
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
public class jsonHelper
{
public static string To<T>(T obj)
{
string retVal = null;
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
retVal = Encoding.Default.GetString(ms.ToArray());
}
return retVal;
}
public static T From<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
}
return obj;
}
}
所以,把你的JSON,并用jsonHelper级以上
So take your json above and send it to the From method in the jsonHelper class above
People peeps = jsonHelper.From<People>(input);
这篇关于使用JSON在C#.NET 3.5工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!