0

My object it looks like that

{"Items":[{number:8468},{}],

 "count":2}

I need to take for example number of item 1

my code is that and it is not working

var content = await response.Content.ReadAsStringAsync();
var myObject = JsonConvert.DeserializeObject<ICollection<ViewModel>>(content);
InUser
  • 1,138
  • 15
  • 22
Alexa
  • 5
  • 5
  • 2
    Does this answer your question? [Deserialize a JSON array in C#](https://stackoverflow.com/questions/16856846/deserialize-a-json-array-in-c-sharp) – InUser Oct 05 '20 at 12:19

2 Answers2

1

The JSON here represents an object, not a collection - which is to say: the outer node is {}, not []. As such, create a type that reflects that:

public class Foo {
    public List<Bar> Items {get;} = new List<Bar>();
    [JsonProperty("count")]
    public int Count {get;set;}
}
public class Bar {
    [JsonProperty("number")]
    public int Number {get;set;}
}

and use:

var myObject = JsonConvert.DeserializeObject<Foo>(content);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Here you have a json object not json array. So your logic is failing. So first create a model like this :

public class Response {

    public List<Item> Items {get;set;} = new List<Item>();
    public int Count {get;set;}
}

public class Item {
    public int Number {get;set;}
}

and replace :

var myObject = JsonConvert.DeserializeObject<ICollection<ViewModel>>(content);

with

var result = JsonConvert.DeserializeObject<Response>(content);