0

Please Help me out i am new in xamarin.forms and C# i have try every solution which is given in stackoverflow but cannot avail to solve

 using (var httpClient = new HttpClient())
 {
   var response = httpClient.GetAsync(Url).Result;
   if (response.IsSuccessStatusCode)
   {
      var responseContent = response.Content;
      string contents = await responseContent.ReadAsStringAsync();
      List<abcModel> tm = JsonConvert.DeserializeObject<List<abcModel>>(contents);
      abcMaster = new ObservableCollection<SummaryModel>();
      var c = tm[0].SSum.Count();
   }
} 

Model

public class abcModel
{
  public List<SSum> SSum { get; set; }
}
public class SSum
{
  public string Name{ get; set; }
}

My Json

{"a":[{"SSum":[{"Name":"Earth"}]}]}

Error:-

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[abcModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

DavidG
  • 113,891
  • 12
  • 217
  • 223
Atul Dhanuka
  • 1,453
  • 5
  • 20
  • 56

3 Answers3

3

Because you obviously just want to deserialize a nested part of your json, do it like this:

var result = JsonConvert.DeserializeObject<Dictionary<string, List<abcModel>>>(json);
stefankmitph
  • 3,236
  • 2
  • 18
  • 22
0

You're missing the a property in your JSON. You can deserialize into a class that has that property:

public class MyType
{
    public List<abcModel> A { get; set; }
}

JsonConvert.DeserializeObject<MyType>(json);

Or skip that property all together (@stefankmitph's answer works well), here's another alternative:

JObject obj = JObject.Parse(json);

List<abcModel> model = obj["a"].ToObject<List<abcModel>>();

Just a note: normally C# classes are PascalCased.

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

If you already have the JSON string you should use a generator like json2csharp to create the response DTO. This will prevent mistakes in what is a collection versus single object.

public class SSum
{
    public string Name { get; set; }
}

public class A
{
    public List<SSum> SSum { get; set; }
}

public class RootObject
{
    public List<A> A { get; set; }
}

Now you can deserialize the complete object:

tm = JsonConvert.DeserializeObject<RootObject>(contents);
SKall
  • 5,234
  • 1
  • 16
  • 25