How to add jarray Object into JObject - c#

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.

Related

Serialize flat Dictionary into multi-sub-object JSON

In C# I have a flat Dictionary<string, string> where keys are in form of obj1/obj2/obj3 and values are direct string. Now I want to serialize that into subobjects, so example values:
var dict = new Dictionary<string, string> { {"foo/bar/baz1", "123" }, {"foo/baz", "456" }, { "foo/abc", "def" } };
should result with:
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}
Optionally I want to remove quotes around "123" and "456" in output if they can be interpreted as numbers or booleans.
I am using Newtonsoft.JSON
You can parse a source dictionary into JObject using JObject.FromObject method. Then go through all of properties, split them using string.Split and parse recursively to a new JObject, representing a properties tree. Finally add this object to the destination one using JObject.Add, or update it if the given key is already exist
var dict = new Dictionary<string, string> { { "foo/bar/baz1", "123" }, { "foo/baz", "456" }, { "foo/abc", "def" } };
var source = JObject.FromObject(dict);
var dest = new JObject();
foreach (var property in source.Properties())
{
//split the name into parts
var items = property.Name.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
var item = items.FirstOrDefault();
if (string.IsNullOrEmpty(item))
continue;
//get JObject representing a properties tree
var result = WriteItems(items.Skip(1).ToList(), property.Value);
//check that destination already contains top property name (e.g. 'foo')
if (dest.ContainsKey(item))
{
(dest[item] as JObject)?.Add(result.First);
}
else
{
dest.Add(item, result);
}
}
Console.WriteLine(dest.ToString());
//local function to recursively go through all properties and create a result JObject
JObject WriteItems(IList<string> items, JToken value)
{
var item = items.FirstOrDefault();
items.RemoveAt(0);
if (!items.Any()) //no more items in keys, add the value
return new JObject(new JProperty(item, value));
return new JObject(new JProperty(item, WriteItems(items, value)));
}
It produces the following output
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}
Also, the code above allows you to handle a properties tree with any depth. I don't think that there is a built-in way to serialize the structure like foo/bar/baz1 into sub-objects in Json.NET

Add array to property

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());

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

return array of arrays instead of array of objects with json.net

I need to return an array of arrays instead of an array of objects for a flot chart.
I can get the following:
data = [{"2012-10": 4140},{"2012-11": 10815},{"2012-12": 10444}];
but need (UPDATE fixed following line):
data = [["2012-10", 4140],["2012-11", 10815],["2012-12", 10444]];
Here is the c# which is parsing inbound json from another source:
public async Task<ActionResult> Chart(string custid)
{
//Get the financial results from DRT
var response = await DominoJSON.getJSON(custid, "drtHistory", "DRT");
JArray UOVol = new JArray();
var array = JArray.Parse(response);
foreach (var token in array)
{
JObject o = JObject.Parse(token.ToString());
int uovol = Convert.ToInt32(o["UOVol"]);
string uodate = o.SelectToken("DATE").ToString();
JObject UOItem = new JObject(new JProperty(uodate, uovol));
UOVol.Add(UOItem);
}
string resultUO = UOVol.ToString();
ViewBag.UOData = resultUO;
return View();
}
And the inbound json being parsed:
[
{
"DATE":"2012-10",
"UOVol":4140,
"FIRev":180,
"AFRev":692.75,
"ABRev":2900,
"OWRev":3791.25,
},
{
"DATE":"2012-11",
"UOVol":10815,
"FIRev":60,
"AFRev":170,
"ABRev":0,
"OWRev":3037.5,
},
{
"DATE":"2012-12",
"UOVol":10444,
"FIRev":40,
"AFRev":514.25,
"ABRev":1450,
"OWRev":7500,
}
]
I can't figure out how to turn the JObjects to arrays. I have tried this with other approaches including using a dictionary and list. Any help or alternate solutions would be helpful. Using VS2013, mvc 5 and EF 6.
Try this:
class Program
{
static void Main(string[] args)
{
string jsonIn = #"
[
{
""DATE"": ""2012-10"",
""UOVol"": 4140,
""FIRev"": 180,
""AFRev"": 692.75,
""ABRev"": 2900,
""OWRev"": 3791.25
},
{
""DATE"": ""2012-11"",
""UOVol"": 10815,
""FIRev"": 60,
""AFRev"": 170,
""ABRev"": 0,
""OWRev"": 3037.5
},
{
""DATE"": ""2012-12"",
""UOVol"": 10444,
""FIRev"": 40,
""AFRev"": 514.25,
""ABRev"": 1450,
""OWRev"": 7500
}
]";
JArray arrayIn = JArray.Parse(jsonIn);
JArray arrayOut = new JArray();
foreach (JObject jo in arrayIn.Children<JObject>())
{
JArray ja = new JArray();
ja.Add(jo["DATE"]);
ja.Add(jo["UOVol"]);
arrayOut.Add(ja);
}
string jsonOut = arrayOut.ToString(Formatting.None);
Console.WriteLine(jsonOut);
}
}
Output:
[["2012-10",4140],["2012-11",10815],["2012-12",10444]]

Create Json dynamically in c#

I need to create a Json object dynamically by looping through columns.
so declaring an empty json object then add elements to it dynamically.
eg:
List<String> columns = new List<String>{"FirstName","LastName"};
var jsonObj = new {};
for(Int32 i=0;i<columns.Count();i++)
jsonObj[col[i]]="Json" + i;
And the final json object should be like this:
jsonObj={FirstName="Json0", LastName="Json1"};
[TestFixture]
public class DynamicJson
{
[Test]
public void Test()
{
dynamic flexible = new ExpandoObject();
flexible.Int = 3;
flexible.String = "hi";
var dictionary = (IDictionary<string, object>)flexible;
dictionary.Add("Bool", false);
var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false}
}
}
I found a solution very similar to DPeden, though there is no need to use the IDictionary, you can pass directly from an ExpandoObject to a JSON convert:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
foo.Test = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
and the output becomes:
{ "FirstName":"John", "LastName":"Doe", "Active":true }
You should use the JavaScriptSerializer. That can Serialize actual types for you into JSON :)
Reference: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
EDIT: Something like this?
var columns = new Dictionary<string, string>
{
{ "FirstName", "Mathew"},
{ "Surname", "Thompson"},
{ "Gender", "Male"},
{ "SerializeMe", "GoOnThen"}
};
var jsSerializer = new JavaScriptSerializer();
var serialized = jsSerializer.Serialize(columns);
Output:
{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}
Using dynamic and JObject
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.StockCount = 9000;
Console.WriteLine(product.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
Or how about:
JObject obj = JObject.FromObject(new
{
ProductName = "Elbow Grease",
Enabled = true,
StockCount = 9000
});
Console.WriteLine(obj.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm

Categories

Resources