112

对于我的一些单元测试,我希望能够构建特定的 JSON 值(在这种情况下是记录专辑),这些值可以用作被测系统的输入。

我有以下代码:

var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");

这很好用,但我从来没有真正喜欢过“魔术字符串”语法,并且更喜欢更接近 JavaScript 中的 expando-property 语法的东西,如下所示:

jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
4

7 回答 7

165

那么,怎么样:

dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
于 2013-08-15T05:34:37.347 回答
81

您可以使用该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 文档

于 2015-01-05T18:04:26.770 回答
53

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 }
        }
    }
};
于 2018-01-12T13:30:57.457 回答
33

在某些环境中,您无法使用动态(例如 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

于 2016-05-12T23:32:14.083 回答
6

迟早您将拥有具有特殊特征的财产。例如创建日期。属性名称中不允许使用连字符。这会破坏你的代码。在这种情况下,您可以使用索引或索引和属性的组合。

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
于 2019-03-21T00:56:09.047 回答
2

从属性创建 newtonsoft JObject 的简单方法。

这是一个示例用户属性

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

我希望 newtonsoft JObject 中的这个属性是:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

输出将是这样的:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
于 2018-08-29T20:04:56.090 回答
-3

您可以使用 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 );
于 2013-08-15T05:43:33.690 回答