Quote:
Actually sir i want show my serialize data just like that - "Data":[{"demo1":123}}] and I'm using query string default.aspx?username=abc & password=ayz after debugging this code, now my data show like that - [{"demo1":123}]
This should be in the question body and not in the comments below.
Firstly, your JSON example is invalid. You can validate your JSON here:
JSON Formatter & Validator[
^]
Correction is:
{
"Data":[
{
"demo1":123
}
]
}
Next, you need to have a class structure to store the data to be converted. My favorite tool is:
JSON Utils: Generate C#, VB.Net, SQL Table, Java and PHP from JSON[
^]
Using this tool the following classes are generated:
public class Datum
{
[JsonProperty("demo1")]
public int Demo1 { get; set; }
}
public class Example
{
[JsonProperty("Data")]
public IList<Datum> Data { get; set; }
}
Now to handle conversion, TheSniper105 has an example above using Newtonsoft's Json.NET library. Here is my helper class, found in my article
Working with JSON in C# & VB[
^]:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Support.CSharp
{
public static class JsonHelper
{
public static string FromClass<T>(T data, bool isEmptyToNull = false,
JsonSerializerSettings jsonSettings = null)
{
string response = string.Empty;
if (!EqualityComparer<T>.Default.Equals(data, default(T)))
response = JsonConvert.SerializeObject(data, jsonSettings);
return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
}
public static T ToClass<T>(string data,
JsonSerializerSettings jsonSettings = null)
{
var response = default(T);
if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject<T>(data)
: JsonConvert.DeserializeObject<T>(data, jsonSettings);
return response;
}
}
}
And to serialize using the above helper class:
var sampleClass = new Example { Data = new List<Datum> { new Datum { Demo1 = 123 }}};
var jsonData = JsonHelper.FromClass(sampleClass);
And to deserialize:
var jsonData = "{"Data":[{"demo1":123}]}";
var sampleClass = JsonHelper.ToClass<Example>(jsonData);
You can learn more from my article
Working with JSON in C# & VB[
^].