1

Is there a way to deserialize a JSON array directly into the property of an object?

I have a JSON consisting of an array of Entry objects. To get them into a Collection class I could go the route of:

var coll = new Collection();
coll.Entries = JsonConvert.DeserializeObject<List<Entry>>(json);

Is there a way to define Collection in a way to skip this step an directly call var coll = JsonConvert.DeserializeObject<Collection>(json)

4
  • I'm not sure, but you can try to let Collection implement IEnumerable<Entry> and see if that works. Commented Jan 23, 2018 at 13:46
  • If yor json is array of Entry objects why it deserialize to object? deserliazation should do same object structure as source. Commented Jan 23, 2018 at 13:52
  • @BWA the request path for the JSON is named in a way that implies getting a collection/single object back, so I want to stick with that. Commented Jan 23, 2018 at 14:51
  • Show examples of JSON. Commented Jan 23, 2018 at 15:16

2 Answers 2

2

You could let your Collection class implement IEnumerable<Entry> and decorate it with the JsonObject attribute. This should give Json.NET the ability to deserialize your class correctly.

[JsonObject]
public class Collection : IEnumerable<Entry>
{
    public IEnumerable<Entry> Entries { get; };

    public GetEnumerator() {
       return Entries.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
       return GetEnumerator();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works if you change [JsonObject] to [JsonArray] and add a constructor that takes an IEnumerable<Entry>. So, like public Collection(IEnumerable<Entry> entries) { this.Entries = entries; }. (Oh, and adding a set; to the Entries property.)
2

While silkfires answer didn't work for me, it gave me a hint for the solution:

I added the [JsonArray] attribute and implemented ICollection<Entry> by pointing all methods to the Entries list.

[JsonArray]
public class Collection: ICollection<Entry>
{

    public LinkedList<Entry> Entries { get; } = new LinkedList<Entry>();

    public void Add(Entry item)
    {
        Entries.AddLast(item);
    }
...

6 Comments

I could have been a bit off. If you remove the JsonObject attribute, does it work then?
I get a Newtonsoft.Json.JsonSerializationException :Cannot create and populate list type for that.
Which type is it referring to?
The Collection type.
@silkfire I added a comment to your answer above. With your solution (and my edits) I did not have to implement the ICollection interface, which is much nicer I think.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.