[英]converting array of string to json object in C#
I have got following scenario where i have a array of strings and i need to pass this data as json object. 我有以下场景,我有一个字符串数组,我需要将此数据作为json对象传递。 How can I convert array of string to json object using DataContractJsonSerializer.
如何使用DataContractJsonSerializer将字符串数组转换为json对象。
code is : 代码是:
string[] request = new String[2];
string[1] = "Name";
string[2] = "Occupaonti";
I would recommend using the Newtonsoft.Json NuGet package, as it makes handling JSON trivial. 我建议使用Newtonsoft.Json NuGet包,因为它使处理JSON变得微不足道。 You could do the following:
您可以执行以下操作:
var request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
var json = JsonConvert.SerializeObject(request);
Which would produce: 哪会产生:
["Name","Occupaonti"]
Notice that in your post you originally were trying to index into the string type, and also would have received an IndexOutOfBounds exception since indexing is zero-based. 请注意,在您的帖子中,您最初尝试索引字符串类型,并且还会收到IndexOutOfBounds异常,因为索引是从零开始的。 I assume you will need values assigned to the Name and Occupancy, so I would change this slightly:
我假设你需要分配给名称和占用的值,所以我会稍微改变一下:
var name = "Pooja Kuntal";
var occupancy = "Software Engineer";
var person = new
{
Name = name,
Occupancy = occupancy
};
var json = JsonConvert.SerializeObject(person);
Which would produce: 哪会产生:
{
"Name": "Pooja Kuntal",
"Occupancy": "Software Engineer"
}
Here's a simple class that should do the job. 这是一个应该完成这项工作的简单课程。 I took the liberty of using Newtonsoft.Json instead of DataContractJsonSerializer.
我冒昧地使用Newtonsoft.Json而不是DataContractJsonSerializer。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
string json = JsonConvert.SerializeObject(request);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.