How to get the properties of json object in C#? - 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

Related

JSON Deserialize Error: The given key was not present in the dictionary

I'm trying to output JSON to a drop down list in a web form. I've managed to get this far:
WebClient client = new WebClient();
string getString = client.DownloadString("http://myfeed.com/app_feed.php");
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["title"];
return name;
This brings back the feed ok but it runs into an error on the line:
string name = item["title"];
Bringing back this error:
Additional information: The given key was not present in the dictionary.
This is a sample of my feed:
{"apps":[{"title":"title1","description":"description1"},
{"title":"title2","description":"description2"},
{"title":"title3","description":"description3"}
So I thought that I was referencing the first title and I was planning to loop through them:
string name = item["title"];
But obviously not!
I have looked on Stackoverflow but I can't find an answer that I can apply to my own code.
title is inside another key apps and its an array so you should iterate it, I show you just select first one using index 0
string name = item["apps"][0]["title"];
you can access all by foreach
foreach (var ap in item["apps"])
{
Console.WriteLine(ap["title"]);
}
First, your JSON is invalid. Second: you need to loop over your items, as it is an array. If you want to access the first one, you could do: item["apps"][0]["title"]
Looping through all items:
var str = #"{""apps"":[{""title"":""title1"",""description"":""description1""},
{""title"":""title2"",""description"":""description2""},
{""title"":""title3"",""description"":""description3""}]}";
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize<object>(str);
foreach (var item in obj["apps"])
{
Console.WriteLine("item title: " + item["title"]);
}

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.

Iterate through dynamic form object

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"]);
}

C# deserialization

How to deserialize with keyvaluepair the above json
string stations = [{"2":false,"1":"Aforre","0":"WS6"},{"2":false,"1":"Alodtau","0":"WS3"},{"2":false,"1":"Balimo Station","0":"WS36"}]
I what like this
var get = js.Deserialize<Dictionary<string,dynamic>>(stations);
try this:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic value = serializer.DeserializeObject(stations);
and you can access objects like:
var a = value[0]["0"];
and a will have "WS6" (according to your JSON)
The JSON shown is an array. You might try desetializing to:
Dictionary<string, object>[]
i.e.
var get = js.Deserialize<Dictionary<string,object>[]>(stations);
One of the best option is create a class that consist of all keyvalue pair and then deserialize json string to the object of created class
You can try using dynamic variable as following:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic serializevalues = serializer.DeserializeObject(stations);
var valueof1 = serializevalues[0]["1"];
Response.Write(valueof1);
The above will print output "Aforre'.

JavaScriptSerializer : Unable to deserialize object containing HashSet field

I am trying to deserialize an instance of the following class from a JSON string using JavaScriptSerializer:
public class Filter
{
public HashSet<int> DataSources { get; set; }
}
Here is the code I am trying out:
Filter f = new Filter();
f.DataSources = new HashSet<int>(){1,2};
string json = (new JavaScriptSerializer()).Serialize(f);
var g= (new JavaScriptSerializer()).Deserialize<Filter>(json);
It errors out with the following message:
Object of type 'System.Collections.Generic.List1[System.Int32]'
cannot be converted to type
'System.Collections.Generic.HashSet1[System.Int32]'.
Apparently, the serializer is unable to distinguish between a list and set from JSON representation. What is the solution to this?
Note : I would prefer avoiding the use of external libraries due to constraints at work.
What is the solution to this?
Use Json.Net. This code works...
Filter f = new Filter();
f.DataSources = new HashSet<int>() { 1, 2 };
string json = JsonConvert.SerializeObject(f);
var g = JsonConvert.DeserializeObject<Filter>(json);
EDIT
DataContractJsonSerializer seems to work too...
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Filter));
var g2 = dcjs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as Filter;
Here's my simple NOT so great solution, but it works.
var dataList = new JavaScriptSerializer().Deserialize<List<int>>(returnData);
var data = new HashSet<int>(dataList);

Categories