-1

I am retrieving the JSON body from an API. I want to deserialize the Json into class and get the specific data I want to append into Picker (Xamarin Forms). I keep on getting error and I am not sure how to resolve this issue. This is my first time doing deserialize so I hope someone can help me on this! Thank you

Error

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'App123.UserDetails[]' 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<T>) 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. Path 'Error', line 1, position 9.'

JSON

{
"Error": null,
"Success": true,
"Data": {
    "Message": "Success",
    "NextPrompt": null,
    "NextDefaultValue": "",
    "IsFinished": false,
    "ReturnData": [
        {
            "User": "M0001",
            "Role": "Admin",
            "Password": "abc2020",
            "Contact": "98780101",
            "Department": "HR"
        },
        {
            "User": "M1043",
            "Role": "Director",
            "Password": "zxy2020",
            "Contact": "91235678",
            "Department": "Finance"
        }
    ]
  }
}

Class

public class UserDetails
{
public class Rootobject
{
public object Error { get; set; }
public bool Success { get; set; }
public Data Data { get; set; }
}

public class Data
{
public string Message { get; set; }
public object NextPrompt { get; set; }
public string NextDefaultValue { get; set; }
public bool IsFinished { get; set; }
public Returndata[] ReturnData { get; set; }
}

public class Returndata
{
public string User { get; set; }
public string Role { get; set; }
public string Password { get; set; }
public string Contact { get; set; }
public string Department { get; set; }
}
}

Code

(code on API connection)
 var response = await client2.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

        string text = responsebody.ToString();
        string[] strText = text.Split(new[] { ',', ':', '}', '{', ']', '[', '\\', '"' }, StringSplitOptions.RemoveEmptyEntries);
UserDetails[] userdetails = JsonConvert.DeserializeObject<UserDetails[]>(text);

        UserPicker.ItemsSource = userdetails;
Ris
  • 13
  • 2
  • It's not an array you're deserializing. Try `JsonConvert.DeserializeObject(text);` – ESG May 20 '20 at 02:25
  • Does this answer your question? [Cannot deserialize the JSON array (e.g. \[1,2,3\]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly](https://stackoverflow.com/questions/22557559/cannot-deserialize-the-json-array-e-g-1-2-3-into-type-because-type-requ) The exact duplicate – Pavel Anikhouski May 20 '20 at 07:06

2 Answers2

1

it look like json not match class. maybe try this?

   string text = responsebody.ToString();
   Rootobject userdetails = JsonConvert.DeserializeObject<Rootobject>(text);
TimChang
  • 2,249
  • 13
  • 25
  • Hey thank you! This works well :) I was able to retrieve the values but I can't get it added into the picker... – Ris May 20 '20 at 03:26
0

According to your Json data, you need to deserialize the Rootobject.

Not UserDetails. Plus you don't need to be worry about array as long as your serialize string format is correct.

Here is testing about json serialize/deserialize on your class.

  static void Main(string[] args) 
  {
        // Returndata
        Returndata returndata_1 = new Returndata()
        {
            User = "M0001",
            Role = "Admin",
            Password = "abc2020",
            Contact = "98780101",
            Department = "HR"
        };
        Returndata returndata_2 = new Returndata()
        {
            User = "M1043",
            Role = "Director",
            Password = "zxy2020",
            Contact = "91235678",
            Department = "Finance"
        };
        Returndata[] returndatas = { returndata_1, returndata_2 };

        // Data
        Data data = new Data()
        {
            Message = "Success",
            NextPrompt = null,
            NextDefaultValue = "",
            IsFinished = false,
            ReturnData = returndatas
        };

        // Rootobject
        Rootobject rootobject = new Rootobject()
        {
            Error = null,
            Success = true,
            Data = data
        };

        string serializeText = JsonConvert.SerializeObject(rootobject);
        Rootobject deserializeObj = JsonConvert.DeserializeObject<Rootobject>(serializeText);

        Console.ReadLine();  
  }
funbrain9
  • 503
  • 6
  • 15