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";
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#.
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.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With