我有一個 api 以這種格式回傳資料
{ "reult":
{ "70":
{
"type_id": 3,
"type": "forex",
"group_title": "forex",
"name": "EUR",
"title": "EUR"
},
"724":
{
"type_id": 5,
"type": "shares",
"group_title": "shares",
"name": "#ABT",
"title": "#ABT"
}
}
}
現在我想要這些關鍵物件對資料到一個真正的 C# 物件陣列。像這樣
[
{
Id = 70
Type_id = 3,
Type = "forex",
Group_title = "forex",
Name = "EUR",
Title = "EUR"
},
{
Id = 724,
Type_id = 5,
Type = "shares",
Group_title = "shares",
Name = "#ABT",
Title = "#ABT"
}
]
有可能這樣做嗎?[我已經更新了api回傳的資料。因為使用這種格式可以很容易地使用 c# 字典對這些資料進行消毒]
uj5u.com熱心網友回復:
創建具有這些屬性的類,然后使用以下代碼:
JsonSerializer.Deserialize<List<object>>(jsonString);
這是更多詳細資訊的鏈接:
https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
uj5u.com熱心網友回復:
假設你有一些課程:
public class Root
{
[JsonProperty("result")]
public Dictionary<int, Data> Result {get;set;}
}
public class Data
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("type_id")]
public int TypeId { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("group_title")]
public string GroupTitle { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
}
您可以取消原始資料(不是您通過洗掉“結果”修改的資料),然后呼叫,如果您想要一個陣列:
var root = JsonConvert.DeserializeObject<Root>(str);
foreach(var kvp in root.Result) kvp.Value.Id = kvp.Key;
var arr = root.Result.Values.ToArray();
ps; 您需要參考 Newtonsoft.Json;System.Collections.Generic; System.Linq;
uj5u.com熱心網友回復:
當我將您的 json 反序列化為 c# 類時,它是正確的類物件,也許您的 json 不正確
它是 c# 類:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class _70
{
public int type_id { get; set; }
public string type { get; set; }
public string group_title { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class _724
{
public int type_id { get; set; }
public string type { get; set; }
public string group_title { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class Reult
{
public _70 _70 { get; set; }
public _724 _724 { get; set; }
}
public class Root
{
public Reult reult { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/381560.html
標籤:javascript C# 数组 。网 目的
上一篇:將屬性附加到物件陣列中的每個物件
