Kliver Max
Kliver Max

Reputation: 5299

How to deserialize json string in c#?

I have a json string:

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

I want to parse it (my json sting already in byte[] array):

  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);

But i get exeption:

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

Whats wrong here?

Update

I'd edit my class:

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

How i not get any exeptions but after deserialize i get object with empty fields.

Update2

When i tried parse json string:

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

my code works fine. But how to deserialize a array of objects like this:

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

Upvotes: 1

Views: 139

Answers (2)

Levan
Levan

Reputation: 642

DataContractJsonSerializer requires that classes must be marked with DataContract attribute(and properties with DataMember), like this:

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

Or use JSON.NET libraries, which doesn't require attributes, and has very easy syntax:

JsonConvert.DeserializeObject(json);

Upvotes: 2

Cris
Cris

Reputation: 13341

try this

[DataContract]
private class MyClass
    {

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

Upvotes: 2

Related Questions