简体   繁体   中英

List change to the json format

I want to change list to json format. How can I do?

        var db = new TelephoneBookDataContext();

        List<string> Capitals = (from U in db.Users
                                 where U.Name.ToLower().StartsWith(name.ToLower())
                                 select U.Name).ToList();
        return Capitals;

Java script part I cant get as such this code part

 $("document").ready(function () {
        $("#<%= txtSearch.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "Show.aspx/GetName",
                    data: "{'name':'" + $("#<%= txtSearch.ClientID %>").val() + "'}",
                    dataType: "json",
                    type: "POST",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        console.log(result);
                    }
                });
            },
            minLength: 2
        });
    });

First Add Name space

using System.Web.Script.Serialization;

Then use JavaScriptSerializer class

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);

your List is of String Type so you might need this try below if above donot work.

string[][] ArrayCapitals = Capitals.Select(x => new string[]{x}).ToArray();

string json = JsonConvert.SerializeObject(ArrayCapitals );

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