4

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

5
  • Have you tried "reflecting" it? Commented Oct 12, 2009 at 10:32
  • JSON.net is open source and I am going through code now, but nothing so far. Commented Oct 12, 2009 at 10:33
  • Suggestion: How about going through the documentation some before you start looking at the source code? (james.newtonking.com/projects/json/help) Commented Oct 12, 2009 at 10:54
  • 2
    Most of the documentation there is auto generated from source code Commented Oct 12, 2009 at 10:59
  • I couldn't agree more! It's reference at best. I've been fighting through the exact same scenario... the default (de)serializers aren't working so we have to write our own. No clue at all with that documentation! Commented May 4, 2011 at 4:46

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
You are right. Seems, the easiest way is to implement some collection interface in the Label - IList or ICollection.
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.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.