2 回答

TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
1)您需要創(chuàng)建一個枚舉,其中包含owner_type在 json中具有價值的所有可能成員
[JsonConverter(typeof(StringEnumConverter))]
public enum EnumOwnerType
{
[EnumMember(Value = "App\\Models\\User")]
User,
[EnumMember(Value = "App\\Models\\Group")]
Group
}
您需要添加對項目的引用以進(jìn)行組裝System.Runtime.Serialization
,并且在您的程序中您必須導(dǎo)入一些名稱空間,例如
using System.Runtime.Serialization;
對于EnumMemberAttribute。using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
對于StringEnumConverter。using Newtonsoft.Json.Linq;
對于JObject。
2)修改你的Vehicle
類如下
public class Vehicle
{
[JsonProperty("owner_type")]
public EnumOwnerType OwnerType { get; set; }
[JsonProperty("owner")]
public JObject Owner { get; set; }
}
在以上類別中的屬性
OwnerType是類型EnumOwnerType。
Owner是類型JObject。
3)這是您的示例模型User
class User
{
public int id { get; set; }
public string username { get; set; }
public string email { get; set; }
public string email_verified_at { get; set; }
public DateTime? created_at { get; set; }
public DateTime? updated_at { get; set; }
}
這是為了Group
class Group
{
public int id { get; set; }
public string name { get; set; }
public DateTime? created_at { get; set; }
public DateTime? updated_at { get; set; }
public _Color color { get; set; }
}
class _Color
{
public int id { get; set; }
public string hex { get; set; }
public DateTime? created_at { get; set; }
public DateTime? updated_at { get; set; }
}
用法:反序列化代碼
string json = "Your json here";
Vehicle vehicle = JsonConvert.DeserializeObject<Vehicle>(json);
switch (vehicle.OwnerType)
{
case EnumOwnerType.User:
User user = vehicle.Owner.ToObject<User>();
break;
case EnumOwnerType.Group:
Group group = vehicle.Owner.ToObject<Group>();
break;
}
在上面switch的塊中,案例根據(jù)OwnerType枚舉自動執(zhí)行,并且Owner是JObject將您的ownerjson 對象類型轉(zhuǎn)換為適當(dāng)?shù)哪P蚒ser或Group。
輸出:(來自調(diào)試器)
1) 對于你的第一個帶有"owner_type": "App\\Models\\User".
2) 對于你的第二個 json"owner_type": "App\\Models\\Group"

TA貢獻(xiàn)1877條經(jīng)驗 獲得超1個贊
只是反序列化為動態(tài)。您可以使用 ExpandoObject 獲得所需內(nèi)容。
var converter = new ExpandoObjectConverter();
dynamic customer1 = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
Console.WriteLine(customer1.owner.username);
- 2 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報