how can i C# Deserialize JSON list WinForm Combobox? - c#

I would like to print out the contents of the array selected in Combo Box 2 after selecting an item in Combo Box 1.
Like this picture
{
"Movie": [
"Action",
{
"Mad Max": "1979",
"Terminator": "1984"
},
"SF",
{
"Star Wars": "1979"
}
]
}
The JSON file looks like this
The class is defined like this:
public class Root
{
public List<object> Movie { get; set; }
}
But I don't know how to read what's in the object.
I appreciate any help provided. Thanks in advance.

Assume that the Movie property contains a pattern with the action type first followed by a dictionary/object,
Deserialize JSON as Root.
Get the index from root.Movie by matching the value with the selected action type.
Deserialize the next item by the index (index + 1) in root.Movie as Dictionary<string, string> type.
using System.Collections.Generic;
using System.Text.Json;
Root root = JsonSerializer.Deserialize<Root>(json);
int index = root.Movie.FindIndex(x => x.ToString() == selected);
Dictionary<string, string> dict = JsonSerializer.Deserialize<Dictionary<string, string>>(root.Movie[index + 1].ToString());
// Print output
foreach (KeyValuePair<string, string> kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
Sample .NET Fiddle

Related

C# Get JSON Keys from Array without Model

I have a JSON file
{
"RandonName": [
{
"RandomKey1": "Data",
"RandomKey2": "Data",
"RandomKey3": "Data",
"RandomKey4": "Data",
"RandomKey5": "Data"
},
{
"RandomKey1": "Data",
"RandomKey2": "Data",
"RandomKey3": "Data",
"RandomKey4": "Data",
"RandomKey5": "Data"
}
]
}
My Deserializer
JsonTextReader JTR = new JsonTextReader(stringReader);
JsonSerializer JS = new JsonSerializer();
var dictionary = JS.Deserialize(JTR) as IEnumerable<KeyValuePair<string, JToken>>;
My Print, output is RandonName
foreach(KeyValuePair<string, JToken> pair in sourceRoot)
{
Console.WriteLine(pair.Key);
}
Can I get somehow all Key names inside the array?
JsonSerializer.Deserialize() is a static method. You don't need to create instance for JsonSerializer.
Meanwhile JToken is from Newtonsoft.Json. I think would be great not to mix up with System.Text.Json and Newtonsoft.Json.
And deserialize as Dictionary<string, List<Dictionary<string, string>>> type.
Dictionary<string, List<Dictionary<string, string>>> dictionary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(JTR);
// Iterate for first item in RandonName dictionary
foreach (KeyValuePair<string, string> kvp in dictionary["RandonName"][0])
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
// Iterate for all items in RandonName dictionary
foreach (var items in dictionary["RandonName"])
{
foreach (KeyValuePair<string, string> kvp in items)
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
}
Sample .NET Fiddle
To get all Keys (from the first item):
dictionary["RandonName"][0].Keys
To get all keys from every item in the list:
using System.Linq;
dictionary["RandonName"].SelectMany(x => x.Keys).ToList();
string json = #"{
'RandonName': [
{
'RandomKey1': 'Data',
'RandomKey2': 'Data',
'RandomKey3': 'Data',
'RandomKey4': 'Data',
'RandomKey5': 'Data'
},
{
'RandomKey1': 'Data',
'RandomKey2': 'Data',
'RandomKey3': 'Data',
'RandomKey4': 'Data',
'RandomKey5': 'Data'
}
]
}
";
Console.WriteLine(
JObject.Parse(json)["RandonName"][0].Children<JProperty>().Select(x => x.Name));
Will print out:
RandomKey1
RandomKey2
RandomKey3
RandomKey4
RandomKey5
The key to the one-liner is to cast the children of the first JObject to JProperty.
If you need only just the property names from the first object then you can take advantage of Json.NET's Linq
var semiParsedJson = JObject.Parse(json);
var collection = (JArray)semiParsedJson["RandonName"];
var firstObject = (JObject)collection.First();
foreach (var property in firstObject.Properties())
{
Console.WriteLine(property.Name);
}

How to include description in JSON file using Dictionary C#

I'm starting using C# and have a lot to learn.
I'm trying to create a JSON file with a dictionary (thats easy).
JsonSerializer.Serialize(MyDictionary)
But it returns the data without descriptions...
{
"-0255504",
"1"
},
{
:"08000301",
:"1"
}
I want to to include some descriptions like:
{
"ArticleId":"-0255504",
"OrderedQuantity":"1"
},
{
"ArticleId":"08000301",
"OrderedQuantity":"1"
},
{
"ArticleId":"03820235",
"OrderedQuantity":"1"
}
For sure is easy to include and don't want to use List for my program.
Is available any method or property to modify the format?
I'm Using System.Text.Json;
You can project your dictionary items into anonymous (or not anonymous) types to get your property names:
Dictionary<string, string> d = new Dictionary<string, string>
{
{ "-0255504", "1" },
{ "-08000301", "1" },
};
string json = JsonSerializer.Serialize(d.Select(entry => new { ArticleId = entry.Key, OrderedQuantity = entry.Value }));

How to deserialize JSON to IList<KeyValuePair<string, object>> with whitespaces in key?

I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.
"spec": {
"SOMETHING WITH SPACES" : "10"
etc.
...
}
public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}
Deserializing code:
var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);
responseJson is a GET from ElasticSearch.
What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>
You can't use IList or List here, because your source JSON has no [ ] in it, which is a requirement if you want to parse into such a collection. In other words, without [ ] you can't parse into a collection, at least not without going through lots of hoops.
Instead you need to use a Dictionary as was suggested already in comments.
Note: I used Newtonsoft JsonConvert because you didn't state what your parser is, but that should make little or no difference to my arguments.
Working code:
var json = "{ \"spec\": { \"SOMETHING WITH SPACES\" : \"10\" } }";
var someObj = JsonConvert.DeserializeObject<SomeObject>(json);
public class SomeObject
{
public Dictionary<string, object> spec{ get; set; }
}
After that, you can cast the spec property to an IEnumerable and loop through whatever was found:
foreach (var pair in someObj.spec as IEnumerable<KeyValuePair<string, object>>)
{
Console.WriteLine(pair.Key + " -> " + pair.Value);
}
Or even convert it to a List:
var list = someObj.spec.ToList();
foreach (var pair in list)
{
Console.WriteLine(pair.Key + " -> " + pair.Value);
}
.NET Fiddle: https://dotnetfiddle.net/15l2R3
If you don't mind using Newtonsoft.Json:
const string json = #"{""spec"": { ""SOMETHING WITH SPACES"" : ""10"", ""SOMETHING WITH MORE SPACES"" : ""20"" }}";
dynamic data = JsonConvert.DeserializeObject(json);
Dictionary<string, string> list = data["spec"].ToObject<Dictionary<string, string>>();
foreach (var item in list)
{
Console.WriteLine(item.Key + ", " + item.Value);
}
I guess your JSON serialiazer makes some trouble. I'd recommend to use Newtonsoft.Json (in NuGet)
I've tried following code, and it works fine:
var o1 = new SomeObject() { spec = new List<KeyValuePair<string, object>>() };
o1.spec.Add(new KeyValuePair<string, object>("test with spaces", 10));
var r1 = Newtonsoft.Json.JsonConvert.SerializeObject(o1);
Console.WriteLine(r1);
var o2 = Newtonsoft.Json.JsonConvert.DeserializeObject<SomeObject>(r1);
var r2 = Newtonsoft.Json.JsonConvert.SerializeObject(o2);
Console.WriteLine(r2);
The outcome is
{"spec":[{"Key":"test with spaces","Value":10}]}
{"spec":[{"Key":"test with spaces","Value":10}]}
No null values, all works fine.
EDIT: I actually see no reason, why spaces should be any problem at all. They are just part of the string.

Get key value pair from JSON string

I have a json string like
{
[
"EnrityList": "Attribute",
"KeyName": "AkeyName",
"Value": "Avalue"
],
[
"EnrityList": "BusinessKey",
"KeyName": "AkeyName",
"Value": "Avalue"
]
}
I have serialized and got an object array.
Could anyone help me to get the key value pair from these object array.
You can use JsonConvert from Newtonsoft.Json to deserialize json into Dictionary.
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring);
First convert the above string in proper json format by using :
str=str.Replace('[', '{');
str=str.Replace(']', '}');
//replace first occurance of {
int startPos = str.IndexOf('{');
str=str.Substring(0,startPos)+" ["+str.Substring(startPos + 1);
//replace last occurance of }
int endPos = str.LastIndexOf('}');
str=str.Substring(0,endPos)+"]";
This makes the string
str = [{"EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"}, {"EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"} ]
Now, since you got the json string, you can easily work with it.
we can use method as given by
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
Looking at your example, You are trying to receive a List of certain type of elements,
So First, You will need a class to represent your data type.
class MyType
{
string EnrityList;
string KeyName;
string Value;
}
Then use DesrializeObject method to store it in the variable
var values = JsonConvert.DeserializeObject<List<MyType>>(jsonstring);

Dictionary<string, List <KeyValuePair<string,string>>>

I have created:
Dictionary<string, List <KeyValuePair<string,string>>> diction = new Dictionary<string, List<KeyValuePair<string,string>>>();
Later I've added to that list:
diction.Add(firststring, new List<KeyValuePair<string,string>>());
diction[firststring].Add(new KeyValuePair<string, string>(1ststringlist, 2ndstringlist));
So now, If I want to read and show on screen this dictionary, how would I do it with foreach loop ? It's like 3 dimmension syntax, don't now how to create it and access it.
Also can anyone explain how to read this part?
diction[firststring].Add
What this marks [] excatly mean? I read whole dictionary there?
thank You for answer and Your time.
Dictionaries store key / value pairs. In your case, your key type is string and value type is List <KeyValuePair<string,string>>.So when you do:
diction[firststring]
firststring is your Key and you are trying to access a List <KeyValuePair<string,string>>.Your best option is nested loops I think.if you want to display all values. For example:
foreach(var key in dict.Keys)
{
// dict[key] returns List <KeyValuePair<string,string>>
foreach(var value in dict[key])
{
// here type of value is KeyValuePair<string,string>
var currentValue = value.Value;
var currentKey = value.Key;
}
}
For printing the datastructure, try this:
// string.Join(separator, enumerable) concatenates the enumerable together with
// the separator string
var result = string.Join(
Environment.NewLine,
// on each line, we'll render key: {list}, using string.Join again to create a nice
// string for the list value
diction.Select(kvp => kvp.Key + ": " + string.Join(", ", kvp.Value)
);
Console.WriteLine(result);
In general, to loop over the values of a dictionary, you can use foreach or LINQ just like with any IEnumerable data structure. IDictionary is an IEnumerable>, so the foreach variable will be of type KeyValuePair.
The syntax diction[key] allows you to get or set the value of the dictionary stored at the index key. It's similar to how array[i] lets you get or set the array value at index i. For example:
var dict = new Dictionary<string, int>();
dict["a"] = 2;
Console.WriteLine(dict["a"]); // prints 2
If all you need to do is store rows of 3 string values each, then the data structure you are using is far too complicated.
Here's a much simpler example, based on the Tuple class:
public class Triplet : Tuple<string, string, string>
{
public Triplet(string item1, string item2, string item3) : base(item1, item2, item3)
{
}
}
So you just define a class Triplet that holds 3 strings, like above. Then you simply create a List of Triplets in your code:
// Your code here
var data = new List<Triplet>();
// Add rows
data.Add(new Triplet("John", "Paul", "George"));
data.Add(new Triplet("Gene", "Paul", "Ace"));
// Display
foreach(Triplet row in data)
{
Console.WriteLine("{0}, {1}, {2}", row.Item1, row.Item2, row.Item3);
}
and this is far simpler to read, understand, and maintain.

Categories