Iterate through dynamic form object - c#

Using mvc i get values like this to avoid class declarations and router changes.
public dynamic Create([FromBody] dynamic form)
{
var username = form["username"].Value;
var password = form["password"].Value;
var firstname = form["firstname"].Value;
...
I like to iterate through all values and check them for null or empty.

If you get a json from the argument, you could convert it to an Dictionary<string, dynamic> where the string key is the name of the property and the dynamic is a value that can assume any type. For sample:
var d = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(form);
var username = d["username"];
You also could loop between Keys property from the Dictionary<>:
foreach(var key in d.Keys)
{
// check if the value is not null or empty.
if (!string.IsNullOrEmpty(d[key]))
{
var value = d[key];
// code to do something with
}
}

This is quite old, but I came across this and am wondering why the following was not proposed:
var data = (IDictionary<string, object>)form;

You can use JavaScriptSerializer and dynamic object:
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic myDynamicObject = serializer.DeserializeObject(json);
For example, if you want to loop through myDynamicObject["users"]:
foreach (KeyValuePair<string, dynamic> user in myDynamicObject["users"]){
Console.WriteLine(user.Key+": "+user.Value["username"]);
Console.WriteLine(user.Key+": "+user.Value["email"]);
}

Related

How to convert json key value array to DTO in C# [duplicate]

I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();

How to get the properties of json object in C#?

I am getting the json (objArr) object using the following code:
var objArr = (object[])record.Value;
The code at runtime looks like this:
The json object objArr contains the list of rows, how can I retrieve the properties of rows?
I am able to list the properties with the following loop:
foreach (var obj in objArr)
{
foreach(var item in (Dictionary<string, object>)obj)
{
}
}
but I want to retrieve the properties directly from objArr
try this according to your onject specification
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;
// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];
you can refer this

Getting property/object-name from JSON-List in C#

I have the following JSON-String:
{"object":{"4711":{"type":"volume","owner":"john doe","time":1426156658,"description":"Jodel"},"0815":{"type":"fax","owner":"John Doe","time":1422900028,"description":"","page_count":1,"status":"ok","tag":["342ced30-7c34-11e3-ad00-00259073fd04","342ced33-7c34-11e3-ad00-00259073fd04"]}},"status":"ok"}
A human readable screenshot of that data:
I want to get the Values "4711" and "0815" of that data. I iterate through the data with the following code:
JObject tags = GetJsonResponse();
var objectContainer = tags.GetValue("object");
if (objectContainer != null) {
foreach (var tag in objectContainer) {
var property=tag.HowToGetThatMagicProperty();
}
}
At the position "var property=" I want to get the values "4711".
I could just use String-Manipulation
string tagName = tag.ToString().Split(':')[0].Replace("\"", string.Empty);
but there must be a better, more OOP-like way
If you get the "object" object as a JObject explicitly, you can access the Key property on each member inside of the JObject. Currently objectContainer is a JToken, which isn't specific enough:
JObject objectContainer = tags.Value<JObject>("object");
foreach (KeyValuePair<string, JToken> tag in objectContainer)
{
var property = tag.Key;
Console.WriteLine (property); // 4711, etc.
}
JObject exposes an implementation of IEnumerable.GetEnumerator that returns KeyValuePair<string, JToken>s containing the name and value of each property in the object.
Example: https://dotnetfiddle.net/QbK6MU
I got the results using this
foreach (var tag in objectContainer)
{
var property = tag.Path.Substring(tag.Path.IndexOf(".") + 1);
Console.WriteLine(property);
}
}
Console.ReadLine();
}

Read Json object and put the values in a List of string

Platform: C#
IDE: Visual Studio 2010
I am trying to read all the values from json object and put it in the list of string , for which I am doing Json deserialize but it throws me error...
Here is what I have tried
List<string> lstPName = new List<string>();
JavaScriptSerializer strJsonSer = new JavaScriptSerializer();
localhost.Pstats objStats = new localhost.Pstats();
var strJson = objStats.GetAutoCompleteData(txtSearchBox.Text.Trim());
lstPName = strJsonSer.DeserializeObject<string>(strJson);
Here is what the Json object holds
[{"PlayerName":"WA Mota"},{"PlayerName":"Atif Ahmed"}]
So, I need the player name value to be added in the list...
Simple and straightforward solution:
var strJson = "[{\"PlayerName\":\"WA Mota\"},{\"PlayerName\":\"Atif Ahmed\"}]";
var strJsonSer = new JavaScriptSerializer();
var list = new List<string>();
var result = strJsonSer.DeserializeObject(strJson) as object[];
if (result != null)
{
foreach (Dictionary<string, object> x in result)
{
list.Add(x["PlayerName"].ToString());
}
}
Or, if you are preferring LINQ - you can use instead of foreach loop something like:
list = result
.Cast<Dictionary<string, object>>()
.Select(x => x["PlayerName"].ToString())
.ToList();
Key idea: DeserializeObject used for parsing JSON data like yours gives you array of Dictionary<string, object> where key is JSON property name and value is JSON property value. Size of array equals to objects count in your JSON data.

Deserializing JSON with dynamic keys

I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();

Categories