howto iterate dynamic array - c#

I have the following json string
[{"field1":"1","field2":"2","field3":"3"}{"field1":"11","field2":"22","field3":"33"}{"field1":"111","field2":"222","field3":"333"}]
I use the following code to parse it -
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(s);
How can I iterate the dynamic data array ?

using System.IO;
using System.Web.Script.Serialization;
namespace Deserialize
{
class Program
{
static void Main()
{
string jsonString = File.ReadAllText("dynamic.json");
var serializer = new JavaScriptSerializer();
dynamic data = serializer.Deserialize<dynamic>(jsonString);
foreach (var item in data)
{
foreach (var subitem in item)
{
System.Console.WriteLine("Key={0}, Value={1}", subitem.Key, subitem.Value);
}
System.Console.WriteLine();
}
System.Console.ReadKey();
}
}
}
I need to add commas to separate the 3 objects in the json file for this to work ... but I think this is (roughly) what you are after. Sorry if I have misunderstood.

I ended up using the following code.
List<myClass> l = JsonConvert.DeserializeObject<List<myClass>>(jsonString);
Than I had no problem iterate through l.
myClass is a local class with the field definition, need to make sure field and class defined public.

Related

Can I create some components with a dynamic name on c#? [duplicate]

Can we create dynamic variable in C#?
I know my below code is threw error and very poor coding. But this code have small logic like create dynamic variable
var name=0;
for(i=0;i<10;i++)// 10 means grid length
{
name+i=i;
}
var xx1=name1;
var xx2=name2;
var xx3=name3;
Is it possible in c#? Create dynamic variable in c#? and change the variable name in c#? and concatenate the variable name in c#(like we can concatenate any control id or name)...
Why I need the dynamic variable name (scenario):
var variablename=""
var variablename0=No;
var variablename1=Yes;
var variablename2=No;
.
.
.
I have a gridview with multiple rows. And I need assign server side variable to every row. So I need set of variables in server side. the only I can set Text=<%# variablename+rowCount%> for every template field.
This rowCount means every grid row index.
If the grid has 2 rows, Then rowCount values are 0,1,2
Now I need to change the variablename to variablename0,variablename1,variablename2 dynamically for separate row.
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
No. That is not possible. You should use an array instead:
name[i] = i;
In this case, your name+i is name[i].
Variable names should be known at compile time. If you intend to populate those names dynamically at runtime you could use a List<T>
var variables = List<Variable>();
variables.Add(new Variable { Name = inputStr1 });
variables.Add(new Variable { Name = inputStr2 });
here input string maybe any text or any list
try this one, user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
This is not possible, it will give you a compile time error,
You can use array for this type of requirement .
For your Reference :
http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

C# Create Deedle DataFrame from JSON response

I'm having a bit of trouble loading a JSON response from this request into a Deedle DataFrame:https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?where=OBJECTID%3C10&returnGeometry=false&f=json
In the JSON, what I'm interested are the features. More specifically, for each feature there are attributes - I want essentially just a collection of those attributes to load into a DataFrame. In this particular case, there is only one attribute "name" so my expectation is that the resulting DataFrame would have a column "name" with the values shown.
I've tried using json2csharp and creating my own class, but the result either doesn't have the column header/values or the values are missing. I'm not really sure what I'm doing wrong or if I'm even approaching this the right way. My understanding from the Deedle documentation is that it should be possible to create a DataFrame from a collection of objects: https://bluemountaincapital.github.io/Deedle/csharpframe.html#Creating-and-loading-data-frames. Certainly, using the Enumerable example listed on the page works as expected.
Here is the pertinent section of my code:
string url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?";
WebClient wc = new WebClient();
wc.QueryString.Add("where", "OBJECTID<10");
wc.QueryString.Add("returnGeometry", "false");
wc.QueryString.Add("f", "json");
var data = wc.UploadValues(url, "POST", wc.QueryString);
var responseString = UnicodeEncoding.UTF8.GetString(data);
JObject o = JObject.Parse(responseString);
dynamic x = JsonConvert.DeserializeObject(responseString);
var testObjList = new List<dynamic>();
foreach (dynamic element in x.features)
{
testObjList.Add(new myClass { name = element.attributes.name});
Console.WriteLine($"{element.attributes.name}");
}
var dfObjects = Frame.FromRecords(testObjList);
dfObjects.Print();
var df = Frame.FromRecords(test);
df.Print(); // No headers or values shown
where myClass is just this:
public class myClass{
public string name { get; set; }
}
Any help/pointers would be much appreciated!
The Frame.FromRecords operation relies on static type information to figure out what properties the class has. In your case, you define the list of objects as List<dynamic> - this is compiled as Object and so Deedle does not see any members.
To fix this, all you need to do is to define the type as a list of myClass objects:
var testObjList = new List<myClass>();
A more compact approach using an anonymous type would work too:
var testObjList =
((IEnumerable<dynamic>)x.features).Select(element =>
new { name = element.attributes.name });
var dfObjects = Frame.FromRecords(testObjList);

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

How to serialize a multiple list of elements in Json?

I have a JSON that looks like this:
{
"Identifier1":"TextOfIdentifier1",
"Identifier2":"TextOfIdentifier2",
"Identifier3":"TextOfIdentifier3",
...
}
I know how to deseralize a JSON into a custom object, I followed what says here, but all identifiers appear in the same JSON tag...
How can I get all identifiers inside the JSON?
The solution is like this in my case:
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
JObject jsonLines = JObject.Parse(json);
foreach (var token in jsonLines)
{
dtos.Add(new TokenDto { HalId = token.Key, SourceText = token.Value.ToString() });
}
}
You can traverse JSON (similar to XDocument):
var json = "{\"Identifier1\":\"TextOfIdentifier1\",\"Identifier2\":\"TextOfIdentifier2\",\"Identifier3\":\"TextOfIdentifier3\"}";
foreach (var token in JObject.Parse(json).Children())
Console.WriteLine(token.Path);
Result:
Identifier1
Identifier2
Identifier3

JSON Deserialization: How to get values out of a JSON array of objects

I've successfully deserialized this JSON string in C#, but can't extract the values from the objects nested in the array:
JavaScriptSerializer js = new JavaScriptSerializer();
string json =
{"key":"1234","status":"ok","members":
[{"id":7,"name":"Joe"},
{"id":2,"name":"Robert"},
{"id":18,"name":"Tim"}
]
}
var d = js.Deserialize < dynamic > (json);
string _key = d["key"]; // this works
Array _members = d["members"]; // this works, length = 3
But I'm having trouble extracting the values out of the objects by name, e.g, this isn't right, but essentially I want
_members[0]["name"] or, _members[0].name
I think the deserializer makes the objects inside the array dictionaries, but I think I'm clearing missing something...
I recommend using Json.NET to do what you're doing. The following code does what you want:
JObject jObject = JObject.Parse(json);
JToken memberName = jObject["members"].First["name"];
Console.WriteLine(memberName); // Joe
Via LINQ to Json.
Update:
var js = new JavaScriptSerializer();
var d = js.Deserialize<dynamic>(json);
Console.WriteLine(d["members"][0]["name"]); // Joe
Also works fine.
It's a bit late for an answer but I've been trying to figure this out and thought I should post somewhere what worked for me.
I wanted to use foreach so:
foreach (var member in json["members"])
{
Console.WriteLine(member["name"]);
}
and by the way, (for some reason like in my project) if you have nested arrays, e.g.
string json =
{"key":"1234","status":"ok",
"members":[
{"items"[
{"id":7,"name":"Joe"},
{"id":2,"name":"Robert"},
{"id":18,"name":"Tim"}
]}
]}
Then:
foreach (var member in json["members"])
{
foreach (var item in member["items"])
{
Console.WriteLine(item["name"]);
}
}
You were quite close in syntax. The key here is that d["members"] is of type Object[] / object[]. Instead of Array, you can use dynamic[] and everything works just fine.
Also note that even this declaration isn't explicitly necessary, as shown in DPeden's updated sample.
Here is the code for your updated snippet (I used a console app to test):
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic d = js.Deserialize<dynamic>(json);
string key = d["key"];
string status = d["status"];
dynamic[] members = d["members"];
Console.WriteLine("key = {0}", key);
Console.WriteLine("status = {0}", status);
Console.WriteLine("members.length = {0}", members.Length);
Console.WriteLine("members type name = {0}", members.GetType().Name);
Console.WriteLine("d[\"members\"] type name = {0}", d["members"].GetType().Name);
And here is additional code showing array and member access.
Console.WriteLine("--");
for (int i = 0; i < members.Length; i++)
{
Console.WriteLine("members[{0}][\"id\"] = {1}", i, members[i]["id"]);
Console.WriteLine("members[{0}][\"name\"] = {1}", i, members[i]["name"]);
}
Console.WriteLine("--");
Console.WriteLine("{0}", d["members"][0]["id"]);
Console.WriteLine("{0}", d["members"][0]["name"]);
Console.ReadKey();

Categories