Click here to Skip to main content
15,904,156 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
//This is my code and i want to pass api with array name please give me the answer

protected void Page_Load(object sender, EventArgs e)
{
    //IsTrue = 0;
    if (string.IsNullOrEmpty(Request.QueryString["Username"]) == false
       && string.IsNullOrEmpty(Request.QueryString["Password"]) == false)
    //{
    //    IsTrue = 1;
    //}
    //if (IsTrue > 0)
    {
        DataTable dt = new DataTable();
        
        UserName = Request.QueryString["UserName"];
        Password = Request.QueryString["Password"];
        
        con.Open();
        dt.Load(new SqlCommand("select Top 10 Memberid,MemberName from PartyMaster Order by msrno", con).ExecuteReader());
        con.Close();

        System.Web.Script.Serialization.JavaScriptSerializer serializer
            = new System.Web.Script.Serialization.JavaScriptSerializer();
        
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = default(Dictionary<string, object>);

        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
    }

    //string Mystr = serializer.Serialize(rows);

    string Mystr = serializer.Serialize(rows);

    Response.ContentType = "application/json"; //JSON Text output
    Response.Write(Mystr);
}


What I have tried:

How can i store Object Json in Array Json with Array name ?

please give me the answer
Posted
Updated 18-Sep-17 19:21pm
v3
Comments
Graeme_Grant 18-Sep-17 1:19am    
What is happening?
Satyanand Bhardwaj 18-Sep-17 3:13am    
string Mystr = serializer.Serialize(rows);
i want to use Mystr json object store in Array json with name and pass this array name to api
Graeme_Grant 18-Sep-17 5:33am    
I asked not what you want but what is happening. You are serializing - I can't run your code here, you need to explain. Do you get an error? Is the JSON data output not as expected? What is happening?
Satyanand Bhardwaj 18-Sep-17 6:41am    
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}]
Graeme_Grant 18-Sep-17 6:49am    
so you don't need help then.

i prefare the json.net libraray

more information about it found in the following link


exmaple of what you want

C#
using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Product
{
	public string Name
	{
		get;
		set;
	}

	public DateTime Expiry
	{
		get;
		set;
	}

	public string[] Sizes
	{
		get;
		set;
	}
}

public class Program
{
	public static void Main()
	{
		Product product = new Product();
		product.Name = "Apple";
		product.Expiry = new DateTime(2008, 12, 28);
		product.Sizes = new string[]{"Small"};
		
		
		List<Product> productsArr = new List<Product>{
		
          product,
		  product	
		};
		
		var dataObj = new
		{
		Data = productsArr
		}

		;
		string json = JsonConvert.SerializeObject(dataObj);
		Console.WriteLine(json);
	}
}


i created runnable demo at
the following link
 
Share this answer
 
Comments
Satyanand Bhardwaj 19-Sep-17 8:28am    
thanking you sir
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:
JavaScript
{
   "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:
C#
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[^]:
C#
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:
C#
var sampleClass = new Example { Data = new List<Datum> { new Datum { Demo1 = 123 }}};
var jsonData = JsonHelper.FromClass(sampleClass);

And to deserialize:
C#
var jsonData = "{"Data":[{"demo1":123}]}";
var sampleClass = JsonHelper.ToClass<Example>(jsonData);

You can learn more from my article Working with JSON in C# & VB[^].
 
Share this answer
 
Comments
Satyanand Bhardwaj 19-Sep-17 8:27am    
Thanks a lot ...
It's working and easy to understand.
I have created a method to read and convert it to Dictionary. You can change it according to your need. My code is as follows:

C#
public static Dictionary<string, string> ValidateJsonRequiredValue(JObject jsonData, string[] parameters, string[] nonMandatoryParam)
{
    if (jsonData == null || !jsonData.HasValues)
    {
        return null;
    }

    Dictionary<string, string> parametersValue = new Dictionary<string, string>();
    string retValue;

    foreach (string key in parameters)
    {
        retValue = GetJsonParameterValue(jsonData, key);
        if (retValue == null)
            return null;

        parametersValue.Add(key, retValue);
    }

    if (nonMandatoryParam == null)
        return parametersValue;

    foreach (string key in nonMandatoryParam)
    {
        retValue = GetJsonParameterValue(jsonData, key);
        parametersValue.Add(key, retValue);
    }

    return parametersValue;
}

public static string GetJsonParameterValue(JObject jsonData, string parameterName)
{
    string retValue = string.Empty;
    if (jsonData != null)
    {
        JToken obj = jsonData.GetValue(parameterName, StringComparison.CurrentCultureIgnoreCase);
        return obj == null ? null : Convert.ToString(obj);
    }

    return retValue;
}
 
Share this answer
 
Comments
Satyanand Bhardwaj 19-Sep-17 8:29am    
thanks for this solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900