简体   繁体   中英

how to create a custom JSON in C# and what should the return value be?

i want create a custom json data from the mssql 2008 results so that my iPhone could consume it.

i can consume json websites like this without a problem: json link

the format could look like this:

Place: New York
       Hotel: Widget Hotel
       Telephone: 0305525253

which format should i return to consume it on the iPhone? an array a string, dictionary? i don't know

EDIT: here is my code:

    namespace WebService1
{
    public class LandHelper
    {
        internal static string[] Land()
        {
            List<string> landObject = new List<string>();

            using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
            using (SqlCommand cmd = new SqlCommand(@"SELECT BEZEICHNUNG FROM LAND", con))
            {
                con.Open();
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        if (rdr["BEZEICHNUNG"] != DBNull.Value)
                        {
                            landObject.Add(rdr["BEZEICHNUNG"].ToString());
                        }
                    }
                }
            }
            return landObject.ToArray();
        }
    }
}

i tried this but i don't know how to add a key to the values i get from the database. i think it would be easier when i create a custom json format .

Okay, if I've understood this correctly what you're trying to do is stringify a collection of objects to JSON, and then read them in your iPhone app. I'm assuming you're asking for how to convert from object-to-JSON , and that you've already covered JSON-to-object . I'll cover object-to-JSON here.

What you'll need to do is create a class that contains all of the information you need in your JSON file, like so.

public class Location
{
    public string Place { get; set; }
    public string Hotel { get; set; }
    public string Telephone { get; set; }
}

Now, inside your database reader statement, you'll want to construct a List<Location> , and then add each Location to this list. Once you've done this, you'll easily be able to convert the collection to JSON using the JSON.NET framework... which makes converting objects to JSON as easy as:

// "locations" is the name of the collection
JsonConvert.SerializeObject(locations);

JSON .NET Documentation

Hope this helps. :)

Just Return a List like

  [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public List<StandortHelper.REGION> LAND()
    {
        return StandortHelper.LAND();
    }

You can return easy a JSON-FORMAT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM