简体   繁体   中英

C# deserializing JSON to Dictionary<int,Tuple<string,int>>

I have a JSON file with the structure:

[ {"unit_id": {"type":[string],"customer_id":[int]} },

...,

...]

And I want to convert it to a dictionary (or anything useful) of the structure:

Dictionary<int,Tuple<string,int>>

I am trying the following:

Dictionary<int, Tuple<string,int>> units =
JsonConvert.DeserializeObject<Dictionary<int, Tuple<string, int>>>
(File.ReadAllText(jsonFile));

Which fails because the file can't be deserialized into that structure. I have also tried creating a class:

class Unit{
    public int unitID;
    public Tuple<string, int> details;
}

And then:

List<Unit> units = JsonConvert.DeserializeObject<List<Unit>>(File.ReadAllText(jsonFile));

Which doesn't fail, but doesn't fill the list with any values.

Thanks

For your JSON structure, you may need to create class like this:

    class Unit
    {
        public CustomerType UnitId;
    }

    class CustomerType
    {
        public int CustomId { get; set; }
        public string Type { get; set; }
    }

Or use dynamic :

        Unit unit = new Unit();
        unit.UnitId = new CustomerType()
        {
            CustomId = 1001,
            Type = "Customer"
        };

        //generate test json string
        string jsonTest = JsonConvert.SerializeObject(unit);

        //convert to dynamic
        var result = JsonConvert.DeserializeObject<dynamic>(jsonTest);
        Console.WriteLine(result.UnitId.CustomId);
        Console.WriteLine(result.UnitId.Type);

So I managed to create my dictionary with the following (messy) code:

public static Dictionary<int, Tuple<string, int>> parseJsonIntoDictionary(string jsonFile) {
    Dictionary<int, Tuple<string, int>> unitDictionary = new Dictionary<int,Tuple<string,int>>();
    var json = System.IO.File.ReadAllText(jsonFile);
    var units = JArray.Parse(json);
    foreach (JToken unit in units) {
        JProperty property = ((JObject)unit).Properties().ToArray()[0];
        int unitID = Convert.ToInt32(property.Name);
        Tuple<string,int> tempTuple = new Tuple<string,int>(Convert.ToString(unit[property.Name]["unit_type"]),Convert.ToInt32(unit[property.Name]["customer_id"]));
        unitDictionary[unitID] = tempTuple;
    }
    return unitDictionary;
}

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