How to create 2 dimensional json object in chsarp - c#

We can write 1 dimensional json-object in csharp like this
var Obj = new { username = "Test", password = "TEST" };
How would you write the two dimensional json-object, something like
var Obj = new { username: {[username:"Test", password: "TEST"]}, key:{[Key1:"OK"]} };

What you are creating is not actually a JSON object. It has nothing to do with JSON, though I can see why you thing it does based on the syntax. It is actually an anonymous type.
You can nest these types inside each other, like so (translating your example):
var Obj = new
{
username = new
{
username = "Test",
password = "TEST"
},
key = new
{
Key1 = "OK"
}
};

Related

How to convert list to expandobject key in c#?

I have a function in which i am getting data(array of objects) from db and then adding those objects of array one by one into a lit of type ExpandoObject
public async Task<List<ExpandoObject>> GetGroupWithMaxTickets(){
List<ExpandoObject> topGroupsWithMaxTickets = new List<ExpandoObject>();
dynamic ticketDetails = new ExpandoObject();
var pipeline_tickets = new BsonDocument[]{
new BsonDocument("$match",
new BsonDocument
{
{ "nsp", "/sbtjapan.com" },
{ "datetime",
new BsonDocument
{
{ "$gte", "2019-12-03T00:00:34.417Z" },
{ "$lte", "2019-12-03T24:00:34.417Z" }
} }
}),
new BsonDocument("$group",
new BsonDocument
{
{ "_id", "$group" },
{ "totalTIckets",
new BsonDocument("$sum", 1) }
}),
new BsonDocument("$project",
new BsonDocument
{
{ "_id", 0 },
{ "group", "$_id" },
{ "totalTIckets", 1 }
}),
new BsonDocument("$sort",
new BsonDocument("totalTIckets", -1)),
new BsonDocument("$limit", 5)
};
var collection = await DbService.tickets.AggregateAsync<RawBsonDocument>(pipeline_tickets, new AggregateOptions {UseCursor = true, BatchSize = 500});
await collection.MoveNextAsync();
if(collection.Current.ToList().Count > 0){
// ticketDetails = JsonConvert.DeserializeObject(collection.Current.ToJson());
// ticketDetails.group = collection.Current.ToList()[0]["group"];
// ticketDetails.totalTickets = collection.Current.ToList()[0]["totalTIckets"];
Parallel.ForEach(collection.Current.ToList(), (ticket) => {
Console.WriteLine("Ticket----"+ticket);
dynamic groupWithTickets = new ExpandoObject();
groupWithTickets = ticket;
topGroupsWithMaxTickets.Add(groupWithTickets);
});
}
return topGroupsWithMaxTickets;
}
But it throws an error like this
System.AggregateException: One or more errors occurred. (The best overloaded method match for 'System.Collections.Generic.List<System.Dynamic.ExpandoObject>.Add(System.Dynamic.ExpandoObject)' has some invalid arguments)
I want that my function must return array of objects of type List<ExpandoObject>
How can i do this in c#?
Since you have changed the question, following is the answer that should resolve your matters.
How to NOT work with ExpandoObjects
I tested this on my system and got it to reproduce the same results as you are getting. Following is the failed try:
dynamic employee = new ExpandoObject();
List<ExpandoObject> listOfEmployees = new List<ExpandoObject>();
employee = "someStrangeString";
listOfEmployees.Add(employee); // ERROR !!!!
and just as expected, i get the following error on Add.
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message=The best overloaded method match for 'System.Collections.Generic.List.Add(System.Dynamic.ExpandoObject)' has some invalid arguments
Source=
StackTrace:
Corrected way of ExpandoObject use
Following is the method that will take care of the issues with Adding it to the list.
Parallel.ForEach(collection.Current.ToList(), (ticket) =>
{
Console.WriteLine("Ticket----" + ticket);
dynamic groupWithTickets = new ExpandoObject();
groupWithTickets.users = ticket; //<---- Assign ticket to users element.
topGroupsWithMaxTickets.Add(groupWithTickets);
});
What was done to fix it?
When you are working with ExpandoObjects, you have to think of dictionary type of a deal. When you declare ExpandoObject, you have to dynamically assign the value to an element (that you define).
Example from MS site: shows the proper use of ExpandoObject
dynamic employee, manager;
employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;
Hopefully this resolves your issue.
It should be like this;
dynamic ticketDetails = new ExpandoObject();
ticketDetails.user = collection;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ticketDetails);
You can simply do this:
dynamic ticketDetails = new ExpandoObject();
ticketDetails = Json(new users = JsonConvert.DeserializeObject(collection.Current.ToJson()));
For testing purposes, i used an array arr that holds one of the elements. If you need that array to be part of ExtendoObject with first element being users, you can create a Json object and set the array as value to the "users" element.
dynamic ticketDetails = new ExpandoObject();
JArray arr = new JArray();
arr.Add(#"[{""name"": ""Alex"", ""age"": 21}]");
JObject o = new JObject();
o["users"] = arr.ToString();
ticketDetails = o;
// output: { "users" : [{"name" : "Alex", "age" : 21}]}

Sentry - adding arbitrary key/value pairs to the user context

In the following documentation, it states that you can
...provide arbitrary key/value pairs beyond the reserved names and those will be stored with the user
In C# code, I have the following:
var _user = new {
Login = "fred",
EmailAddress = "fred#here.com",
Name = "Fred Flintstone"
}
SentrySdk.ConfigureScope( scope => {
scope.User = new Sentry.Protocol.User()
{
Id = _user.Login,
Email = _user.EmailAddress,
Username = _user.Login
};
});
Is there a way to add Name (or any other field)? Or is the documentation just referring to tags?
You can add your custom user data via the Other property.
The latest version of the Sentry.Protocol has Other as a IReadOnlyDictionary which means you need to assign a new instance like:
var sut = new User
{
Id = "user-id",
Email = "test#sentry.io",
IpAddress = "::1",
Username = "user-name",
Other = new Dictionary<string, string>
{
{"Name", "your name"},
{"anything else", "whatever"},
}
};
This PR is making Other mutable so you can add data like:
var user = new User();
user.Other.Add("key", "value");

How do I deserialize an array of JSON objects to a C# anonymous type?

I have no problem deserializing a single json object
string json = #"{'Name':'Mike'}";
to a C# anonymous type:
var definition = new { Name = ""};
var result = JsonConvert.DeserializeAnonymousType(json, definition);
But when I have an array:
string jsonArray = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
I am stuck.
How can it be done?
The solution is:
string json = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
var definition = new[] { new { Name = "" } };
var result = JsonConvert.DeserializeAnonymousType(json, definition);
Of course, since result is an array, you'll access individual records like so:
string firstResult = result[0].Name;
You can also call .ToList() and similar methods on it.
You can deserialize to dynamic object by this.
dynamic result = JsonConvert.DeserializeObject(jsonArray);
One approach is to put an identifier in your JSON array string.
This code worked for me:
var typeExample = new { names = new[] { new { Name = "" } } };
string jsonArray = #"{ names: [{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]}";
var result = JsonConvert.DeserializeAnonymousType(jsonArray, typeExample);

Creating C# Objects Dynamically

Currently having an issue creating a reusable object that I will need to use in a JSON construct string function.
Currently I have the following to create the bulk of the JSON string:
var data = new
{
record = new
{
value1 = Row.value1,
value2 = Row.value2,
form_values = new Dictionary<string, string>()
}
};
data.record.form_values["833b"] = Row.value3.ToString();
data.record.form_values["98wq"] = BuildMultiSelectList(Row.value3.ToString());
public object BuildMultiSelectList(string datavalue)
{
var choicelist = new {
choice_values: [datavalue],
other_values: [],
};
return choicelist;
}
The top half all works fine, though the function BuildMultiSelectList is giving errors such as "choice_values" does not exist in the current context and datavalue does not exist in the current context.
Any insight on why this has gone a bit rouge will be appreciated.
May be you are just mixing colon : with =?
var choicelist = new {
choice_values = new string[] {datavalue},
other_values = new[] {},
};

JsonConvert.SerializeObject adds default Result name

Whenever i am trying to Serialize the Object with JsonConvert.SerializeObject it adds a default array name as "d"
json = JsonConvert.SerializeObject(new
{
resultsets = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" },
new Result { id = 3, value = "GSG", info = "DYU" }
}
});
return json;
The Json responce is
{
"d": "{"resultsets":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"},{"id":3,"value":"GSG","info":"DYU"}]}"
}
where extra array added with name "d"
i want simple array as follow
{"resultsets":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"JKL","info":"JKL"},{"id":3,"value":"GSG","info":"DYU"}]}
This is to prevent direct script execution:
Suppose you were returning a plain array. The following is not a valid JS-statement:
{"d": [1]}
whereas this is:
[1]
You can find more information here:
http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/#comment-34045

Categories

Resources