Reputation: 243
I created some C# webservices that output to JSON
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCities() {
SqlConnection myConnection;
SqlCommand myCommand;
SqlDataAdapter myAdapter;
myConnection = new SqlConnection();
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
myCommand = new SqlCommand();
myCommand.CommandText = "Select DISTINCT AddCity, AddState, AddZip from mytable;";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myAdapter = new SqlDataAdapter();
DataSet objDataSet = new DataSet();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(objDataSet);
// Create a multidimensional jagged array
string[][] JaggedArray = new string[objDataSet.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in objDataSet.Tables[0].Rows)
{
JaggedArray[i] = new string[] { rs["AddCity"].ToString(), rs["AddState"].ToString(), rs["AddZip"].ToString()};
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
return strJSON;
}
The output shows like this:
[["UPPER MARLBORO","MD","20772"],["","VA","22301"],["CLINTON","MD","20735"],["GERMANTOWN","MD","20876"],["","VA","22307"],["HUNTINGTOWN","MD","20639"],["GLENARDEN","MD","20774"],["NEWBURG","MD","20664"], <cont...>
I need it to be [["CITY":"UPPER MARLBORO", "ST":"MD", "ZIP":"20772", ....
In short I need fieldnames in the json output. How do I add it into the script? Thanks
Upvotes: 0
Views: 57
Reputation: 1228
The JSON output is exactly as you're describing it in your action. Arrays do not have named fields. You need to use objects if you want named fields. I would use a collection of generic objects, which is more concise and still serializes as an array.
var JaggedArray = new List<Object>();
foreach (DataRow rs in objDataSet.Tables[0].Rows)
{
JaggedArray.Add(new
{
City = rs["AddCity"].ToString(),
State = rs["AddState"].ToString(),
Zip = rs["AddZip"].ToString()
});
}
Upvotes: 1