我從一個外部服務得到了這個奇怪的 API 回應:
{emplooye: "Michael",age:"25",attachments:[{idAttachment: "23",attachmentPath:"C://Users/1"},{idAttachment: "24",attachmentPath:"C://Users/2"}]},{emplooye: "John",age:"30",attachments:{idAttachment: "25",attachmentPath:"C://Users/3"}}
有沒有人遇到過這樣的情況,有時“附件”屬性可以是一個陣列,有時它可以是一個物件?我創建了一個類來操作資料,但是當我找到一個物件時,代碼就會中斷。我在 C# 中這樣做。
使用的類
public class Attachments
{
public string idAttachment{ get; set; }
public string attachmentPath{ get; set; }
}
public class Root
{
public string emplooye {get; set;}
public string age {get;set}
public List<Attachments> attachments { get; set; } = new List<Attachments>();
}
uj5u.com熱心網友回復:
你的json甚至不接近json,應該是這樣的
var json = "[{\"emplooye\":\"Michael\",\"age\":\"25\",\"attachments\":[{\"idAttachment\":\"23\",\"attachmentPath\":\"C://Users/1\"},{\"idAttachment\":\"24\",\"attachmentPath\":\"C://Users/2\"}]},{\"emplooye\":\"John\",\"age\":\"30\",\"attachments\":{\"idAttachment\":\"25\",\"attachmentPath\":\"C://Users/3\"}}]";
使用 Newtonsoft.Json 你可以創建一個 JsonConstructor
using Newtonsoft.Json;
List<Data> data= JsonConvert.DeserializeObject<List<Data>>(json);
public class Data
{
public string emplooye { get; set; }
public string age { get; set; }
public List<Attachments> attachments { get; set; }
[JsonConstructor]
public Data(JToken attachments)
{
if (attachments.Type.ToString() == "Array")
this.attachments = attachments.ToObject<List<Attachments>>();
else
this.attachments = new List<Attachments> { attachments.ToObject<Attachments>() };
}
public Data() {}
}
public class Attachments
{
public string idAttachment { get; set; }
public string attachmentPath { get; set; }
}
uj5u.com熱心網友回復:
您可以使用 Newtonsoft決議為 JToken,它會為您處理輸入,但缺點是沒有穩定且可預測的類來自動反序列化
然后,您需要檢查它的型別,它回傳一個JTokenType 列舉
一旦你知道底層型別是什么,就將資料編組到你的 DTO 類中
JToken responseJT = JToken.Parse(json); //json string
if (responseJT.Type == JTokenType.Array)
//its an array, handle as needed ...
else if (responseJT.Type == JTokenType.Object)
//its an object, handle as needed ...
就個人而言,我會將附件屬性保留為 a List<Attachments>,如果 JToken 具有 JSON 物件,我會將其設定[0]為該屬性的索引。這樣事情就保持一致,您可以輕松地在該屬性上使用 LINQ
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512798.html
標籤:C#数组json目的
