简体   繁体   中英

convert array in json to c# dictionary

i have this json string:

{"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:

// 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. ...

ok - if i set type of name to object, it works correct and set the list of anon objs. ( 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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