JSON.net problem with JsonConvert.DeserializeObject

13,416

Solution 1

By default a class serializes to a JSON object where the properties on the class become properties on the JSON object.

{
    Name: "seq",
    TorrentsInLabel: 1
}

You are trying to serialize it to an array which isn't how the Json.NET serializer works by default.

To get what you want you should create a JsonConverter and read and write the JSON for Label manually to be what you want it to be (an array).

Solution 2

How can JsonConvert know that "seq1" corresponds to name and "1" corresponds to the TorrentsInLabel? Please have a look at JsonObjectAttribute, JsonPropertyAttribute, JsonArrayAttribute

Share:
13,416
grega g
Author by

grega g

c#, some dynamics-crm and sharepoint

Updated on June 04, 2022

Comments

  • grega g
    grega g almost 2 years

    I have the following code and json:

    public class Labels
    {
        public Labels()
        {}
    
        public Label[] Label {get;set;}
    }
    
    public class Label
    {
        public Label()
        { }
        public string Name { get; set; }
        public int TorrentsInLabel { get; set; }
    }
    
    //...
    Labels o = JsonConvert.DeserializeObject<Labels>(json);
    //...
    
    
    {"label": 
    [
      ["seq1",1]
      ,["seq2",2]
    ]}
    

    I would like this array ["seq1","1"] to deserialize into Label object. What am I missing? Some attributes?

    When I run I get exception: Expected a JsonArrayContract for type 'test_JSONNET.Label', got 'Newtonsoft.Json.Serialization.JsonObjectContract'.

    tnx

    gg