How to create JSON string in C#

后端 未结 14 1193
闹比i
闹比i 2020-11-22 12:39

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the

14条回答
  •  一向
    一向 (楼主)
    2020-11-22 13:29

    I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.

    In our asmx we get the data using the variable we passed along

    // return data
    [WebMethod(CacheDuration = 180)]
    public List GetData(int id) 
    {
        var data = from p in db.property 
                   where p.id == id 
                   select new latlon
                   {
                       lat = p.lat,
                       lon = p.lon
    
                   };
        return data.ToList();
    }
    
    public class latlon
    {
        public string lat { get; set; }
        public string lon { get; set; }
    }
    

    Then using jquery we access the service, passing along that variable.

    // get latlon
    function getlatlon(propertyid) {
    var mydata;
    
    $.ajax({
        url: "getData.asmx/GetLatLon",
        type: "POST",
        data: "{'id': '" + propertyid + "'}",
        async: false,
        contentType: "application/json;",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //
            mydata = data;
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            console.log(xmlHttpRequest.responseText);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
    return mydata;
    }
    
    // call the function with your data
    latlondata = getlatlon(id);
    

    And we get our response.

    {"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
    

提交回复
热议问题