简体   繁体   中英

Desserialize json with string,int array - .net core C#

This is my first question on stackoverflow - so far I've always found a solution here:)

I am trying to deserialise JSON object. The problem is the 'count' list, because elements may change - name and value. I think it's best to use the Dictionary for this - but the compiler throws errors.

{
  "count": [
    {"apple": 2},
    {"strawberry": 8},
    {"pear": 2}
  ],
  "on_plate": true,
  "owner": "Billy"
}

my c# class:

    public class FruitsDTO
    {
        public Dictionary<string, int> count { get; set; }
        public bool on_plate{ get; set; }
        public string owner{ get; set; }
    }
var respResponse = JsonConvert.DeserializeObject<FruitsDTO>(jsonObject);

and result: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.

EDITED

Thanks @Phuzi and @Prasad Telkikar:)

I change class to:

    public class FruitsDTO
    {
        public Dictionary<string, int> count { get; set; }
        public Dictionary<string, int> Count2
            {
                get => Count.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value);
            }
        public bool on_plate{ get; set; }
        public string owner{ get; set; }
    }

Count2 - that's exactly what i need.

bool_plate - it's just a typo when renaming in the correct class for the sake of this example

As @Phuzi said, type of count variable should be List<Dictionary<string, int>>> not only Dictionary<string, int>> .

If you notice in json object count property consist of list of fruits, not a single fruit

Update your DTO as below,

public class FruitsDTO
{
    public List<Dictionary<string, int>> count { get; set; }  //Update type to list
    public bool on_plate { get; set; }   //update property name to on_plate
    public string owner { get; set; }
}

Then deserialize,

var respResponse = JsonConvert.DeserializeObject<FruitsDTO>(jsonObject);

2 Options for this

Option 1, use a dictionary with a key value pair.

Option2 define a class for count.

Add another class:

public class FruitsDTO
{
    public List<FruitCounter> count { get; set; }
    public bool bool_plate{ get; set; }
    public string owner{ get; set; }
}

public class FruitCounter
{
    public string value { get; set; }
    public int amount { get; set; }
}

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