C# 使用 JObject 即时创建 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18246716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating JSON on the fly with JObject
提问by Karl Anderson
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.
对于我的一些单元测试,我希望能够构建特定的 JSON 值(在这种情况下是唱片),这些值可以用作被测系统的输入。
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:
这工作正常,但我从来没有真正喜欢“魔术字符串”语法,并且更喜欢像这样的 JavaScript 中更接近于 expando-property 语法的东西:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
采纳答案by Dimitar Dimitrov
Well, how about:
那么,怎么样:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
回答by Nirmal
You can use Newtonsoft library and use it as follows
您可以使用 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 );
回答by Lee Jensen
You can use the JObject.Parse
operation and simply supply single quote delimited JSON text.
您可以使用该JObject.Parse
操作并简单地提供单引号分隔的 JSON 文本。
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.
这具有实际上是 JSON 的好处,因此它读取为 JSON。
Or you have test data that is dynamic you can use JObject.FromObject
operation and supply a inline object.
或者您有动态的测试数据,您可以使用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
}
}
});
回答by Daniele D.
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.
在某些环境中,您不能使用动态(例如 Xamarin.iOS),或者您只是寻找先前有效答案的替代方法。
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
更多文档在这里:http: //www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
回答by Jatin Sanghvi
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:
无论是dynamic
,还是JObject.FromObject
当你有没有有效的C#变量名如JSON性能解决方案的工作"@odata.etag"
。我更喜欢我的测试用例中的索引器初始化语法:
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
和向其添加属性的单独封闭符号集使索引初始化器比经典对象初始化器更具可读性,尤其是在复合 JSON 对象的情况下,如下所示:
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 }
}
}
};
回答by Manjunath Bilwar
Simple way of creating newtonsoft JObject from Properties.
从属性创建 newtonsoft JObject 的简单方法。
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:
我希望 newtonsoft JObject 中的这个属性是:
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"}
回答by PAS
Sooner or later you will have property with special character. 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