21

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";
1
  • 1
    If you can use third party libs, you should take a look to Json.Net Commented Jul 28, 2015 at 9:12

2 Answers 2

43

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"
}
Sign up to request clarification or add additional context in comments.

Comments

6

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

2 Comments

Hi Tom, output of this would be {"Name","Occupation"}... ?
No. As Alex Neves pointed out in his own answer (which is more complete than mine), the output of this is ["Name","Occupaonti"], which in JSON is an array of items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.