简体   繁体   中英

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. How can I convert array of string to json object using DataContractJsonSerializer.

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM