将动态JSON模型转换为C#对象
将动态JSON模型转换为C#对象
这个问题已经有答案了:
我正在开发一个.NET项目。我需要将一个具有动态更改数字节点名称的JSON模型转换为C#类。第二个节点的名称动态变化,因此我不能像这样写一个JsonProperty:[JsonProperty(“ 353503”)]。我没有看到过这样的JSON模型。我尝试了许多方法,但无法实现。我该怎么办?
{ "standings": { "353493": { "id": "353493", "name": "root name", "n": "0", "ut": "2021-08-23T20:54:12+00:00", "standing_participants": { "4273616": { "id": "4273616", "n": "14", "ut": "2021-08-23T20:54:11+00:00", "rank": "1", "standing_data": [ { "id": "146906199", "standing_type_paramFK": "1", "value": "6", "code": "points", "n": "2", "ut": "2021-08-23T20:54:11+00:00", "sub_param": "" }, { "id": "146906200", "standing_type_paramFK": "2", "value": "8", "code": "goalsfor", "n": "2", "ut": "2021-08-23T20:54:11+00:00", "sub_param": "" } ] }, "4273617": { "id": "4273617", "n": "14", "ut": "2021-08-23T20:54:11+00:00", "rank": "2", "standing_data": [ { "id": "146906198", "standing_type_paramFK": "1", "value": "6", "code": "points", "n": "2", "ut": "2021-08-23T20:54:11+00:00", "sub_param": "" }, { "id": "146906201", "standing_type_paramFK": "2", "value": "8", "code": "goalsfor", "n": "2", "ut": "2021-08-23T20:54:11+00:00", "sub_param": "" } ] } } } } }
当我尝试这个时,它可以工作
public partial class SampleStandingModel { [JsonProperty("standings")] public Standings Standings { get; set; } } public partial class Standings { [JsonProperty("353493")] public Standing Standing { get; set; } }
但是当我删除[JsonProperty(“ 353493”)]行时,它就无法工作
public partial class SampleStandingModel { [JsonProperty("standings")] public Standings Standings { get; set; } } public partial class Standings { public Standing Standing { get; set; } //or this: // public Dictionary<int, Standing> Standing { get; set; } }
我的JSON解析代码如下:
var deserializedObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
我问题的重点在于第二个节点(standing - & gt; 353493)名称是数字和动态的。
我的问题标记为以前已回答,但没有同样的问题。旧问题涉及动态类型或对象。这个问题涉及数字和动态节点名称。我两天都没有找到解决方案。
admin 更改状态以发布 2023年5月23日