【发布时间】:2023-03-15 19:33:01
【问题描述】:
我有这个 json 字符串:
{"products": [{"id": 22,"date_add": "2021-06-17 19:21:26","date_upd": "2021-07-12 13:02:01","name": [{"id": "1","value": "Product 1"}, {"id": "2", "value": "Product 1"}]}}, {"id": 1,"date_add": "2021-06-17 18:54:54","date_upd": "2021-06-17 18:54:54","name": [{"id": "1","value": "something321"},{"id": "2","value": "something23"}]}]}
还有这个类:
class Products
{
[JsonProperty("id")]
public override string ExternalId { get; set; }
[JsonProperty("name")]
public Dictionary<string, string> Name { get; set; }
[JsonProperty("date_upd")]
public DateTime DateModified{ get; set; }
}
我想将我的 json 产品映射到产品列表,所以我尝试了这个:
// get "products" array from json
Regex regex = new Regex(@"(?:{""products"":)(.+)(?:})");
MatchCollection matches = regex.Matches(result);
if (matches.Count > 0)
{
result = matches[0].Groups[1].Value;
}
else
{
result = null;
}
//
var deserialized = JsonConvert.DeserializeObject<List<PrestaProducts>>(result);
它抛出:Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'System.Collections.Generic.Dictionary`2[System.String,System.String] ' 因为该类型需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。 ...
好的 - 如果我将名称类型设置为对象,它会正常工作并设置匿名 objs 列表。
(public object Name { get; set; })
但是如何将这些名称设置为字典?
【问题讨论】:
-
您的 json 对象无效..请输入正确的对象,以便我可以帮助您..
-
试试这个 { "products": [ { "id": 22, "name": [ { "id": "1", "value": "Product 1" }, { "id ": "2", "value": "产品 1" } ] }, { "id": 1, "name": [ { "id": "1", "value": "蜂鸟印花 T 恤" }, { "id": "2", "value": "蜂鸟印花 T 恤" } ] } ] }
标签: c# json deserialization json-deserialization