簡體   English   中英

將 Json 反序列化為 class C#

[英]Deserialize Json into class C#

我正在從 API 中檢索 JSON 主體。 我想將 Json 反序列化為 class 並將我想要 append 的具體數據轉換為 Picker(Xamarin Forms)。 我不斷收到錯誤,我不知道如何解決這個問題。 這是我第一次進行反序列化,所以我希望有人可以幫助我! 謝謝

錯誤

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'App123.UserDetails[]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg 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 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;

看起來 json 與 class 不匹配。 也許試試這個?

   string text = responsebody.ToString();
   Rootobject userdetails = JsonConvert.DeserializeObject<Rootobject>(text);

根據您的 Json 數據,您需要反序列化Rootobject

不是UserDetails 另外,只要您的序列化字符串格式正確,您就不必擔心數組。

這是關於 json 在 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();  
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM