Creating JSON on the fly with JObject

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";
175985 次浏览

不如这样:

dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";

你可以使用 Newtonsoft 图书馆,并按以下方式使用

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

您可以使用 JObject.Parse操作并简单地提供单引号分隔的 JSON 文本。

JObject  o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");

这样做的好处是它实际上是 JSON,因此它读取为 JSON。

或者您有动态的测试数据,您可以使用 JObject.FromObject操作并提供一个内联对象。

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

有些环境不能使用动态(例如 Xamarin.iOS) ,有些情况下只能寻找替代以前有效答案的方法。

在这些情况下,你可以这样做:

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

更多文档请点击: Http://www.newtonsoft.com/json/help/html/creatinglinqtojson.htm

如果 JSON 属性不是有效的 C # 变量名,例如 "@odata.etag",那么 dynamicJObject.FromObject解决方案都不能工作。在我的测试用例中,我更喜欢 indexer 初始化程序语法:

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

从 Properties 创建 newtonsoft JObject 的简单方法。

这是一个示例用户属性

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",
});

产出将是这样的:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

迟早你会拥有一个特殊的属性。例如: 创建日期。属性名中不允许使用连字符。这会破解你的密码。在这种情况下,您可以使用索引,也可以使用索引和属性的组合。

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