Skip to main content
 首页 » 编程设计

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

2024年02月13日20cloudgamer

我有一个 json 字符串:

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

我想解析它(我的 json 字符串已经在 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); 

但是我得到了异常(exception):

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." 

这里有什么问题吗?

更新

我会编辑我的类(class):

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

我怎么没有得到任何异常(exception),但反序列化后我得到了空字段的对象。

更新2

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

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

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

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

请您参考如下方法:

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

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

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

JsonConvert.DeserializeObject(json);