views:

1898

answers:

2

Hi

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

+1  A: 

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

darkiri
Are you sure? It is missing Contract not Attribute. I tried putting JsonArrayAttribute on Label and JsonPropertyAttrbiute on Name and TorrentsInLabel, but those attributes want name of property.
grega g
You are right. Seems, the easiest way is to implement some collection interface in the Label - IList or ICollection.
darkiri
yea, but I want from json array to business object.At the moment I am implementing solution by subclassing JsonCoverter, but it wont be perfect.
grega g
+1  A: 

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

James Newton-King