1

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

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Zen, thanks for the answer, but I managed to fix it myself before reading your answer. Thanks though!
@StefanOrr No problem, happy coding!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.