gpt4 book ai didi

c# - 将 JSON 字典反序列化为具有属性的对象

转载 作者:行者123 更新时间:2023-11-30 17:29:15 25 4
gpt4 key购买 nike

我遇到了一个糟糕的 API,它返回以下 JSON:

{
"root":[
{
"row":[
{
"name":"Foo",
"value":"Some value"
},
{
"name":"Bar",
"value":"Some other value"
}, (...)
]
},
{
"row":[
{
"name":"Foo",
"value":"Lorem"
},
{
"name":"Bar",
"value":"Ipsum"
}, (...)
]
}, (...)
]
}

我想使用 Newtonsoft.Json 将其反序列化为 C# 对象列表,这样名称将匹配对象属性,值将是属性值。该类看起来像这样:

class Row
{
public string Foo { get; set; }
public string Bar { get; set; }
(...)
}

有什么想法吗?

最佳答案

您可以使用自定义 JsonConverter 来处理此问题。下面是一个简单的例子,它需要一些空检查等,但这是有道理的:

    public class RowConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Row[]);
}

public override bool CanWrite => false;

public override bool CanRead => true;

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{

if (reader.TokenType == JsonToken.Null)
{
return string.Empty;
}
else if (reader.TokenType == JsonToken.String)
{
return serializer.Deserialize(reader, objectType);
}
else
{
JObject obj = JObject.Load(reader);
var root = obj["root"];
if (root != null)
{
var rows = new List<Row>();
foreach (var item in root)
{
var row = item["row"];
var newRow = new Row();
foreach(var field in row)
{
// better use reflection here to convert name-value to property setter
if (field.Value<string>("name") == "Foo")
{
newRow.Foo = field["value"].Value<string>();
}

if (field.Value<string>("name") == "Bar")
{
newRow.Bar = field["value"].Value<string>();
}
}

rows.Add(newRow);
}

return rows.ToArray();
}
return null;
}
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

然后在你的 Row 类上:

[JsonConverter(typeof(RowConverter))]
public class Row
{
public string Foo { get; set; }

public string Bar { get; set; }
}

如果您需要将其包含在您的 MVC 中,请在 Startup.cs (asp.net core) 中:

services
.AddMvc()
.AddJsonOptions(options => { options.SerializerSettings.Converters.Add(new RowConverter()); });

关于c# - 将 JSON 字典反序列化为具有属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com