For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.
I have the following code:
var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");
This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
Well, how about:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
You can use the JObject.Parse operation and simply supply single quote delimited JSON text.
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
This has the nice benefit of actually being JSON and so it reads as JSON.
Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Json.net documentation for serialization
Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "#odata.etag". I prefer the indexer initializer syntax in my test cases:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = "2Pac"
};
Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = new JObject
{
["Name"] = "2Pac",
["Age"] = 28
}
};
With object initializer syntax, the above initialization would be:
JObject jsonObject = new JObject
{
{ "Date", DateTime.Now },
{ "Album", "Me Against The World" },
{ "Year", 1995 },
{ "Artist", new JObject
{
{ "Name", "2Pac" },
{ "Age", 28 }
}
}
};
There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.
In these cases you can do:
using Newtonsoft.Json.Linq;
JObject jsonObject =
new JObject(
new JProperty("Date", DateTime.Now),
new JProperty("Album", "Me Against The World"),
new JProperty("Year", "James 2Pac-King's blog."),
new JProperty("Artist", "2Pac")
)
More documentation here:
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Sooner or later you will have property with a special character. e.g. Create-Date. The hyphen won't be allowed in property name. This will break your code. In such scenario, You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
May I suggest using the nameof expression combined with a model for the structure you're trying to build?
Example:
record RecordAlbum(string Album, string Artist, int Year);
var jsonObject = new JObject
{
{ nameof(RecordAlbum.Album), "Me Against The World" },
{ nameof(RecordAlbum.Artist), "2Pac" },
{ nameof(RecordAlbum.Year), 1995 }
};
As an added benefit to removing the "magic string" aspect - this also will give you a little bit of refactor-ability. You can easily rename any given property name for the record and it should update the value returned by the nameof() expression.
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );
Trying to get address and its value to be curly brackets. means json object within a json object.
var jsonObject = new JObject();
dynamic j_obj = new JObject();
j_obj.jsonrpc = "1.0";
j_obj.id = "abc";
j_obj.method = "getrawtransaction";
j_obj.#params = new JArray() as dynamic;
dynamic info = new JObject();
info.txid = "myid";
info.vout = "0";
j_obj.#params.Add(info);
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Console.WriteLine(j_obj.ToString());
What I want is "address" and its value to be json object.
This is the output I am getting now.
Output Image
You are adding a value property here
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Instead create an object for the address then use that in the property:
dynamic addressItem = new JObject();
addressItem.line1 = "foo";
var address = "myaddress";
j_obj.Add(new JProperty(address, addressItem));
Alternatively, as you have gone down the dynamics route you could do this
j_obj.myaddress = new
{
line1 = "foo"
}
Either of these would create JSON that looks like this:
{
...
"myaddress": { "line1": "foo" }
...
}
I'm trying to pass a Json that I'd like to access from jquery as,
jdata.comType
my c# code is,
var frontChartList = new List<object>();
frontChartList.Add(new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(frontChartList);
return json;
I cannot access this as
jdata.comType
only as,
jdata[0].comType
how should I create the JSON to get a string accessible as jdata.comType?
since I will only be passing one object in this.
Because your frontChartList is a List<object>, change it to single object instead:
var frontChartList = new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});
In the following code, I have a dictionary "nissi_params_fields" which I have populated with parameters:
Dictionary<string, string> nissi_params_fields = new Dictionary<string, string>();
string[] separator = { "," };
string[] dfields = form_fields.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string[] ffields = db_fields.Split(separator, StringSplitOptions.RemoveEmptyEntries);
foreach (var field in ffields)
{
NissiMain nm = new NissiMain();
object field_object = nm.nissi_get_object_by_name(field);
string fieldvalue = nm.nissi_get_object_value_by_name(field_object);
nissi_params_fields[field] = fieldvalue;
this.nissiSetStorageItem(save_page, field, fieldvalue);
}
nissi_params_fields["company_id"] = this.nissiGetStorageItem("nissi_base", "ni_companyID");
string nissi_params_id = "";
if (save_type == "edit")
{
nissi_params_fields["id"] = this.nissiGetStorageItem(save_page, "id");
nissi_params_id = this.nissiGetStorageItem(save_page, "id");
}
I now want to create an anonymous type that contains the above "nissi_params_fields" dictionary as a single field "fields", so I first try to convert "nissi_params_fields" to an object "nissi_params_fields_object" that I can use in the Newtonsoft JObject "nissi_params_object":
object nissi_params_fields_object = nissi_params_fields.ToArray();
The challenge is how to convert the dictionary to an object ...how do I do this?
I now want to include the converted object "nissi_params_fields_object" in an anonymous type and then serialize the entire thing to JSON using the Newtonsoft JObject:
JObject nissi_params_object = JObject.FromObject(new
{
apikey = this.nissiGetStorageItem("nissi_base", "ni_apiKey"),
company_id = this.nissiGetStorageItem("nissi_base", "ni_companyID"),
id = nissi_params_id,
fields = nissi_params_fields_object,
});
If you just want to JSON serialize the object you can do:
string jsonString = JsonConvert.SerializeObject(nissi_params_object);
and then append jsonString to the URL.
When using the Microsoft namespaces System.Web.Helpers and System.Web.Script.Serialization I expected that the Microsoft serializer played well with Microsofts dynamic JSON object. It turns out that this was a naive assumption. The JavaScriptSerializer serializes the object to "{}". What is the recommended way for this seemingly trivial task?
dynamic obj = new DynamicJsonObject(new Dictionary<string,object>());
obj.FirstName = "Henry";
obj.LastName = "Ford";
JavaScriptSerializer jsc = new JavaScriptSerializer();
string str = jsc.Serialize( obj );
Assert.AreNotEqual(str, "{}"); // Does not fail
Try Json.Net
dynamic obj = new DynamicJsonObject(new Dictionary<string,object>());
obj.FirstName = "Henry";
obj.LastName = "Ford";
string str = JsonConvert.SerializeObject(obj);
It will do it successfully. You can use it with anonymous classes
string s = JsonConvert.SerializeObject(new {FirstName="Henry",LastName="Ford"});
and ExpandoObjects too
dynamic obj = new ExpandoObject();
obj.FirstName = "Henry";
obj.LastName = "Ford";
string s = JsonConvert.SerializeObject(obj);
Deserialization to dynamic objects is also possible
dynamic obj2 = JsonConvert.DeserializeObject(#"{""FirstName"":""Henry"",""LastName"":""Ford""}");
Console.WriteLine(obj2.FirstName + " " + obj2.LastName);