Pooja Kuntal
Pooja Kuntal

Reputation: 471

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";

Upvotes: 21

Views: 102215

Answers (2)

Tom Solacroup
Tom Solacroup

Reputation: 46

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

Upvotes: 6

Alex Neves
Alex Neves

Reputation: 636

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"
}

Upvotes: 43

Related Questions