简体   繁体   English

将json中的数组转换为c#字典

[英]convert array in json to c# dictionary

i have this json string:我有这个 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"}]}]}

and this class:和这个类:

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; }
} 

i want to map my json products to List of Products, so I tried this:我想将我的 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);

it throws: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.它抛出: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' 因为type 需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。 ... ...

ok - if i set type of name to object, it works correct and set the list of anon objs.好的 - 如果我将名称类型设置为对象,它会正常工作并设置匿名对象列表。 ( public object Name { get; set; } ) ( public object Name { get; set; } )

but how can i set that names to dictionary?但是我如何将这些名称设置为字典?

You can convert it to list products您可以将其转换为列表产品

var jsonObj = JsonConvert.DeserializeObject<JsonObjects>(json);
var productObjects = jsonObj.products;

if you want to convert it to dictionary, try this:如果要将其转换为字典,请尝试以下操作:

var products = new Products { products = new List<Product> { } };

    foreach (var item in productObjects)
    {
        var product = new Product
        {
            id = item.id,
            date_add = item.date_add,
            date_upd = item.date_upd,
            name=new Dictionary<string,string>()
        };
        
        foreach (var name in item.name)
        {
            product.name.Add(name.id,name.value);
        }
            products.products.Add(product);
    }

    var productsJson= JsonConvert.SerializeObject( products);
    

OUTPUT输出

{"products":[
{"id":22,"date_add":"2021-06-17 19:21:26","date_upd":"2021-07-12 13:02:01",
"name":{"1":"Product 1","2":"Product 1"}},
{"id":1,"date_add":"2021-06-17 18:54:54","date_upd":"2021-06-17 18:54:54",
"name":{"1":"Hummingbird printed t-shirt","2":"Hummingbird printed t-shirt"}}
]}

classes班级

public class Name
{
    public string id { get; set; }
    public string value { get; set; }
}


public class JsonProduct
{
    public int id { get; set; }
    public string date_add { get; set; }
    public string date_upd { get; set; }
    public List<Name> name { get; set; }
}

public class JsonObjects
{
    public List<JsonProduct> products { get; set; }
}
public class Product
{
    public int id { get; set; }
    public string date_add { get; set; }
    public string date_upd { get; set; }
    public Dictionary<string, string> name { get; set; }
}

public class Products
{
    public List<Product> products { get; set; }
}

What I see from your example, you cannot convert name to Dictionary<string, string> since it's array.我从你的例子中看到,你不能将 name 转换为 Dictionary<string, string> 因为它是数组。 However you can do something like this.但是你可以做这样的事情。 Change this line to include List:更改此行以包含列表:

var deserialized = JsonConvert.DeserializeObject<List<Products>>(result);

and change your model to something like this:并将您的模型更改为如下所示:

public class Products
    {
        [JsonProperty("id")]
        public string ExternalId { get; set; }

        [JsonProperty("name")]
        public List<Dictionary<string, string>> Name { get; set; }

        [JsonProperty("date_upd")]
        public DateTime DateModified { get; set; }
    }

I don't know if this is what you expected or wanted but at least you will fix the error you have at the moment.我不知道这是否是您期望或想要的,但至少您会解决目前的错误。

To me it does not make much sense to have dictionary inside list but you cannot directly convert array to dictionary in a way you tried.对我来说,在列表中包含字典没有多大意义,但您不能以您尝试过的方式直接将数组转换为字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM