Add array to property - c#

I'm trying to find a way to add an array to a property. Currently, I'm adding non-arrys with no trouble.
var root = JObject.Parse(contractJson.ToString());
//get company name node
var companyNameMatches = root.Descendants()
.OfType<JObject>()
.Where(x => x["question"] != null && x["question"].ToString() == "Name of the company");
//add answer result to company name node
foreach (JObject jo in companyNameMatches)
{
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
}
So, this line...how to make "answer" into an array:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
Looking for this output:
"answer":[
{
"result": "value"
}
]

You need your answer property to be an array, so you should use JArray for that. Change this line:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
to:
// Create the object to put in the array
var result = new JObject(new JProperty("result", Request.Form["Companyname"].ToString()));
// Create the array as the value for the answer property
jo.Add("answer", new JArray { result });

This because you are using JObject.
use the JArray object. A JArray is a JContainer, which is a JToken, which you can add to a JObject.
for example, json of users:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string bDay = "2011-05-06";
string email = "dude#test.com";
JObject UpdateTestProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", bDay),
new JProperty("email", email));
Console.WriteLine(UpdateTestProfile.ToString());

Related

How to add fields to JSON object without them existing?

I have a JObject that I am trying to add fields to in a way like this:
JObject dataObject = new JObject();
dataObject[currentSection][key] = val;
currentSection, key and val are all strings, I want it so when its all serialized at the end that it looks something like this:
{
"currentSection": {
"key": "value"
}
}
How would I go about doing this?
You can use JObject.Add() method to add a property to JObject.
Create a JObject for the nested object.
Add property to the nested object.
Add property with nested object to root JObject.
JObject dataObject = new JObject();
JObject nestedObj = new JObject();
nestedObj.Add(key, val);
dataObject.Add(currentSection, nestedObj);
Demo # .NET Fiddle
You have one nested json object inside of the another one. So you have to create a nested currentSection json object before assigning a key to currrentSection
string currentSection = "currentSection";
string key = "key";
string val = "val";
JObject dataObject = new JObject();
dataObject[currentSection] = new JObject();
dataObject[currentSection][key] = val;
or you can do the same in one line
var dataObject = new JObject { [currentSection] = new JObject { [key] = val } };
json
var json = dataObject.ToString();
{
"currentSection": {
"key": "val"
}
}

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}]}

Converting string to JArray

I have to use an API that expects a string containing a an array of json objects.
internal string InitConnect( string RequestData )
{
try
{
dynamic filejsonJarray = new JArray();
filejsonJarray = JArray.Parse(RequestData);
JObject jsonObject = (JObject)filejsonJarray.First;
if (jsonObject.ContainsKey("IP_ADDRESS".ToUpper()))
{
...
}
}
}
In my code I tried different ways of calling this API but don't seem to be able to get the argument right. I have to create an object (connData) using data I have read from a config file (sJSONConfig) and use it as an argument to API; last thing I tried:
string sJSONConfig = Global.ReadJsonConfig();
// returns"{\r\n \"Name\": \"BLAH\",\r\n \"IPAddress\": \"1.2.3.4\",\r\n \"Port\": \"5880\"\r\n}"
JArray filejsonJarray = new JArray();
JObject jsonObject = new JObject();
jsonObject = JObject.Parse(sSJONConfig);
//filejsonJarray = JArray.Parse(sSJONConfig);
//jsonObject = (JObject)filejsonJarray.First;
// Reconnect using new config data
var connData = new
{
NAME = jsonObject.Property("Name").Value.ToString(),
IP_ADDRESS = jsonObject.Property("IPAddress").Value.ToString(),
PORT = jsonObject.Property("Port").Value.ToString(),
Enabled = "true",
Something = "false"
};
string reqData = JsonConvert.SerializeObject(filejsonJarray);
//filejsonJarray.Add(reqData);
InitConnect(reqData);
Obviously, I cannot changed the InitConnect API.
You can create your desired JSON like this:
string sJSONConfig = Global.ReadJsonConfig();
JObject jsonObject = JObject.Parse(sJSONConfig);
JObject connData = new JObject(
new JProperty("NAME", jsonObject["Name"]),
new JProperty("IP_ADDRESS", jsonObject["IPAddress"]),
new JProperty("PORT", jsonObject["Port"]),
new JProperty("Enabled", "true"),
new JProperty("Something", "false")
);
JArray filejsonJarray = new JArray(connData);
string reqData = filejsonJarray.ToString();
InitConnect(reqData);

JObject nested property

I am trying to make a json object like this with JObject:
{
"input": {
"webpage/url": "http://google.com/"
}
}
I can add properties like:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
But any time I try to nest an object inside another object so I can have the parent "input" it throws an exception.
How do you make nested properties with JObject?
Probably the most straightforward way would be:
var input = new JObject();
input.Add("webpage/url", "http://google.com");
var obj = new JObject();
obj.Add("input", input);
Which gives you:
{
"input": {
"webpage/url": "http://google.com"
}
}
Another way would be:
var input = new JObject
{
{ "webpage/url", "http://google.com" }
};
var obj = new JObject
{
{ "input", input }
};
... Or if you wanted it all in one statement:
var obj = new JObject
{
{
"input",
new JObject
{
{ "webpage/url", "http://google.com" }
}
}
};
Just carry on as you are, and nest them in another level:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
JObject parent = new JObject(new JProperty("input", job));
parent.ToString() now gives:
{ "input": {
"website/url": "http://www.google.com" } }

How to add jarray Object into JObject

How to add JArray into JObject? I am getting an exception when changing the jarrayObj into JObject.
parameterNames = "Test1,Test2,Test3";
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
JObject ObjDelParams = new JObject();
ObjDelParams["_delete"] = jarrayObj;
JObject UpdateAccProfile = new JObject(
ObjDelParams,
new JProperty("birthday", txtBday),
new JProperty("email", txtemail))
I need output in this form:
{
"_delete": ["Test1","Test2","Test3"],
"birthday":"2011-05-06",
"email":"dude#test.com"
}
I see two problems with your code as you posted it.
parameterNames needs to be an array of strings, not just a single string with commas.
You can't add a JArray directly to a JObject; you have to put it in a JProperty and add that to the JObject, just like you are doing with the "birthday" and "email" properties.
Corrected code:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string txtBday = "2011-05-06";
string txtemail = "dude#test.com";
JObject UpdateAccProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", txtBday),
new JProperty("email", txtemail));
Console.WriteLine(UpdateAccProfile.ToString());
Output:
{
"_delete": [
"Test1",
"Test2",
"Test3"
],
"birthday": "2011-05-06",
"email": "dude#test.com"
}
Also, for future reference, if you are getting an exception in your code, it is helpful if you say in your question exactly what the exception is, so that we don't have to guess. It makes it easier for us to help you.
// array of animals
var animals = new[] { "cat", "dog", "monkey" };
// our profile object
var jProfile = new JObject
{
{ "birthday", "2011-05-06" },
{ "email", "dude#test.com" }
};
// Add the animals to the profile JObject
jProfile.Add("animals", JArray.FromObject(animals));
Console.Write(jProfile.ToString());
Outputs:
{
"birthday": "2011-05-06",
"email": "dude#test.com",
"animals": [
"cat",
"dog",
"monkey"
]
}
var jObject = new JObject();
jObject.Add("birthday", "2011-05-06");
jObject.Add("email", "dude#test.com");
var items = new [] { "Item1", "Item2", "Item3" };
var jSonArray = JsonConvert.SerializeObject(items);
var jArray = JArray.Parse(jSonArray);
jObject.Add("_delete", jArray);
it is easy,
JArray myarray = new JArray();
JObject myobj = new JObject();
// myobj.add(myarray); -> this is wrong. you can not add directly.
JProperty subdatalist = new JProperty("MySubData",myarray);
myobj.Add(subdata); // this is the correct way I suggest.

Categories

Resources