Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting array of string to json object in C#

Tags:

json

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";
like image 366
Pooja Kuntal Avatar asked Jul 28 '15 09:07

Pooja Kuntal


People also ask

Can we convert string to JSON in C?

Convert String to JSON Object With the JObject. Parse() Function in C# The JObject class inside the Newtonsoft. Json package is used to represent a JSON object in C#.

Can JSON have array of arrays?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

What is a JSONArray?

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.


1 Answers

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"
}
like image 84
Alex Neves Avatar answered Sep 23 '22 07:09

Alex Neves