如何在c#中反序列化json字符串?

时间:2014-02-18 07:54:28

标签: c# json

我有一个json字符串:

[{"Id":[1], "Value":"MyText" }, {"Id":[20, 31], "Value":"AnotherText" },{"Id":[2, 3, 4, 5], "Value":"MyText"}]

我想解析它(我的json sting已经在byte []数组中):

  private class MyClass
    {
        public int[] Id { get; set; }
        public string Value { get; set; }
    }

var stream= new MemoryStream(jsonStr);
var ser = new DataContractJsonSerializer(typeof(MyClass));
var result = (MyClass) ser.ReadObject(stream);

但我得到了解释:

Message "Type 'MyNameSpace.Test+MyClass' cannot be serialized. Consider marking it  
with the DataContractAttribute attribute, and marking all of its members you want   
serialized with the DataMemberAttribute attribute.  If the type is a collection,   
consider marking it with the CollectionDataContractAttribute.  
See the Microsoft .NET Framework documentation for other supported types."

这里有什么问题?

更新

我编辑了我的课程:

  [DataContract]
  private class MyClass
    {
        [DataMember]
        public int[] Id { get; set; }
        [DataMember]
        public string Value { get; set; }
    }

我怎么没有得到任何exeptions但反序列化后我得到空字段的对象。

UPDATE2

当我尝试解析json字符串时:

{"Id":[1], "Value":"MyText" }

我的代码工作正常。但是如何反序列化这样的对象数组:

[{"Id":[1], "Value":"MyText" },{"Id":[2,6], "Value":"MyText2222" },{"Id":[3,4], "Value":"MyText1111" }]

2 个答案:

答案 0 :(得分:2)

试试这个

[DataContract]
private class MyClass
    {

        [DataMember]
        public int[] Id { get; set; }
        [DataMember]
        public string Value { get; set; }
    }

答案 1 :(得分:2)

DataContractJsonSerializer 要求必须使用 DataContract 属性(以及 DataMember 的属性)标记类,如下所示:

[DataContract]
public class Person
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Name { get; set; }
}

或者使用JSON.NET库,它不需要属性,并且语法非常简单:

JsonConvert.DeserializeObject(json);