使用JObject动态创建JSON

时间:2013-08-15 05:14:16

标签: c# json json.net

对于我的一些单元测试,我希望能够构建特定的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";

7 个答案:

答案 0 :(得分:109)

那么,怎么样:

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

答案 1 :(得分:59)

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

答案 2 :(得分:26)

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

答案 3 :(得分:23)

如果您的JSON属性不是有效的C#变量名,则dynamicJObject.FromObject解决方案都不起作用,例如"@odata.etag"。我更喜欢我的测试用例中的索引器初始化器语法:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = "2Pac"
};

使用单独的一组封闭符号来初始化JObject并为其添加属性使得索引初始值设定项比经典对象初始值设定项更具可读性,尤其是在复合JSON对象的情况下,如下所示:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = new JObject
    {
        ["Name"] = "2Pac",
        ["Age"] = 28
    }
};

使用对象初始化器语法,上面的初始化将是:

JObject jsonObject = new JObject
{
    { "Date", DateTime.Now },
    { "Album", "Me Against The World" },
    { "Year", 1995 }, 
    { "Artist", new JObject
        {
            { "Name", "2Pac" },
            { "Age", 28 }
        }
    }
};

答案 4 :(得分:1)

从属性创建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"}

答案 5 :(得分:0)

迟早您将拥有具有特殊字符的属性。您可以使用索引,也可以结合使用索引和属性。

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

答案 6 :(得分:-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 );