Deserialiazing Json dictionary to list [duplicate] - c#

This question already has answers here:
How can I deserialize a child object with dynamic (numeric) key names?
(2 answers)
Closed 4 years ago.
I have a Json file, with the object serialized correctly, but the problem is that the json has what seems like a dictionary with keys that are strings "0","1" and so on.
Is there any way, not involving writing an own parser, to correctly deserialise these into a list?
"WeaponSlots":{
"0":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
},
"1":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
}
Example file: https://pastebin.com/i3LQ3L7j

You can use the datatype Dictionary<string, object> to deserialize this..

static void Main(string[] args)
{
// load the file.
var file = File.ReadAllText("Example.json");
// to generate the 'Example' classes from JSON I used
// https://app.quicktype.io and changed the name to 'Example'
var example = JsonConvert.DeserializeObject<Example>(file);
// select the value of each dictionary entry into a list.
var sections = example.Sections.Select(x => x.Value).ToList();
}

Related

Getting Collection text while serializing List<string> inside a Dictionary using JsonConvert in C# [duplicate]

This question already has answers here:
How can I serialize/deserialize a dictionary with custom keys using Json.Net?
(4 answers)
Closed 6 months ago.
So I have the following data structure defined in my program:
Dictionary<string, Dictionary<List<string>, int>> myTopDict = new Dictionary<string, Dictionary<List<string>, int>>();
Dictionary<List<string>, int> myInnerDict = new Dictionary<List<string>, int>();
int myIntValue=1;
List<string> myListValue=new List<string>();
myListValue.Add("Example Text 1");
myListValue.Add("Example Text 2");
//Here I add to my inner dictionary
myInnerDict.Add(myListValue, myIntValue);
//And finally adding to top dictionary
myTopDict.Add("My Data Set", myInnerDict);
//Serialize here
string result = JsonConvert.SerializeObject(myTopDict);
When I serialize the data structure, I am getting Collection text in the string as shown below:
What am I doing wrong here? Why I am not able to see my data in the serialized result?
For me the main problem that you have in your code is that you are using inside the dictionary as a key a list of string. That's why it's appering like that when you serialize the json
I don't know the expected Json result that you want. But if the idea is to have a collection of values, so change the Dictionary<string, Dictionary<List, int>> to Dictionary<string, Dictionary<string, List>>
Then the serialization will work different
Again, I really don't know the expected output or if that code is what you really want.

Deserialize json to list of KeyValue pairs [duplicate]

This question already has answers here:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
(22 answers)
Closed 4 years ago.
I have the following json:
[
{
"key":"key1",
"value":"val1"
},
{
"key":"key2",
"value":"val2"
}
]
How can I deserialize it into an list/array of NameValuePair<string, string>?
Example:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<List<KeyValuePair<string,string>>>(json);
The above code runs but the data inside the list is null. I can extract the array into an List<Object> though.
First off, you should not be using JavaScriptSerializer, Microsoft even explicitly says that in the JavaScriptSerializer docs.
To deserialize an object in Json.NET the syntax is very similar:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var result = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);
Fiddle here
UPDATE
If you are using .NET Core 3 / .NET 5 or .NET 6, the System.Text.Json library is included without an additional dependency.
The syntax for deserializing with that library is:
var result = JsonSerializer.Deserialize<List<KeyValuePair<string,string>>>(jsonString);

Easily working on a json object

I'm deserializing (or parsing) a json string to a c# object (using Json.NET) and getting a JObject. I want to iterate all the properties with the key "bla", in the same way iterating all xml elements that named "bla" with XElement.Elements("bla").
If it's not possible, I would like to deserialize my json string into a c# object, and work dynamically and recursively on my deserialized json object (my json string can have lists / arrays that can have objects of 2 types.
In the end after editing my object (changing values and removing or adding properties) I need to serialize my object back to a json string.
Which is the best and easiest way to use json serializing and deserializing?
my Json looks like this:
{"Families":{"Family":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}, {"propA":"dhsj", "propB":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}, {"propA":"dhsj", "propB":"fghfgh"}]}]}
in conclusion, the json value is a json object that it's value is a list/array, the list/array can contain 2 "types" of objects, and one of these types also has a property which it's value is a json object that it's value is a list/array, and it goes like this recursively. sometimes the value of one of the props of the type that doesn't have a property which it's value is a json object that it's value is a list/array, can be a list/array itself, that can contain only 1 type of the two mentioned.
If you don't need a strongly-typed object, you can deserialize to a dictionary:
Dictionary<string, object> myObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
And then just use it as a dictionary:
myObject["Property"] = value;
Or
foreach(var propertyKey in myObject.Keys)
{
// do something with each property
Console.WriteLine($"{propertyKey} = {myObject[propertyKey]}");
}
Here's a fiddle
You can serialize it back after you are done
My json looks more like this:
{"Familys":{"Family":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}]}
For JSON like this:
var json = #"{
""Families"":{
""Family"":[
{
""propA"":""Top""
},
{
""propA"":""Top.Lower"",
""Families"":{
""Family"":[
{
""propB"":""propB value""
},
{
""propA"":""Top.Lower.EvenLower"",
""Families"":{
""Family"":[
{
""propA"":""Top.Lower.EvenLower.EvenLower""
}
]
}
}
]
}
}
]
}
}";
Do something like this:
//calling code makes use of "dynamic" to make things clean and readable.
dynamic parsedJson = JsonConvert.DeserializeObject(json);
var allPropAValues = GetPropAValues(parsedJson);
//**** NOTE: this has our extra property ****
var jsonWithExtraStuffProperty = JsonConvert.SerializeObject(parsedJson);
//recursive function that reads AND writes properties
public static List<string> GetPropAValues(dynamic obj)
{
var propAValues = new List<string>();
//**** NOTE: the use of an added property ****
obj.ExtraStuff = new Random().Next();
//if we have a propA value, get it.
if (obj.propA != null)
propAValues.Add(obj.propA.Value);
//iterate through families if there are any. your JSON had Families.Family.
if (obj.Families != null)
foreach (dynamic family in obj.Families.Family)
propAValues.AddRange(GetPropAValues(family));
return propAValues;
}

Parsing complicated Json Array in C# [duplicate]

This question already has an answer here:
Parse JSON string with inconsistent field names
(1 answer)
Closed 7 years ago.
I have a json array:
{
"array":[
{
"Name_0":"Value_0",
"Name_1":"Value_1"
},
{
"Name_2":"Value_2",
"Name_3":"Value_3",
"Name_4":"Value_4",
"Name_5":"Value_5"
}
]
}
The data structures inside the json array are not consistent.
How can I parse them in C#?
Thanks!
One way to do this will be
var serializer = new JavaScriptSerializer();
var data = serializer
.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(input);
This is because your json data structure is like this. For innermost element we have a Dictionary<string, string> which is nested in a generic list which in turn is nested in another generic dictionary.

Enum to Dictionary LINQ [duplicate]

This question already has answers here:
Enum to Dictionary<int, string> in C#
(10 answers)
Closed 8 years ago.
I'm trying to convert an Enumeration to a Dictionary using LINQ
Here is what I have so far:
// returns a dictionary populated with the relevant keys
public Dictionary<string, string> StartNewEntry()
{
return Enum.GetNames(typeof(TableDictionary)).ToDictionary(Key =>
(string)Enum.Parse(typeof(TableDictionary), Key), value => "");
}
Its giving me issues when trying to cast the key.
Unable to cast object of type 'InventoryImportExportLibrary.TableDictionary' to type 'System.String'.
I'm looking for this:
public enum TableDictionary
{
Barcode = 0,
FullName = 1,
Location = 2,
Notes = 3,
Category = 4,
Timestamp = 5,
Description = 6
}
With a dictionary thats
["Barcode", ""]
I'm not sure what suits does here. I do want the string because I need to use it later in my program for comparisons.
I think want you really want is
Enum to List See: Convert an enum to List
But if you really need a Dictionary take a look at Enum to Dictionary c#

Categories