我只是使用XmlWriter创建了一些XML,以便在HTTP响应中发回。如何创建JSON字符串?我猜你会使用stringbuilder来构建JSON字符串,然后将响应格式化为JSON?


当前回答

包括:

使用System.Text.Json;

然后像这样序列化你的object_to_serialize: JsonSerializer.Serialize (object_to_serialize)

其他回答

如果你想避免创建一个类和创建JSON,那么创建一个动态对象和序列化对象。

            dynamic data = new ExpandoObject();
            data.name = "kushal";
            data.isActive = true;

            // convert to JSON
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

读取JSON并像这样反序列化:

            // convert back to Object
            dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

            // read a particular value:
            output.name.Value

ExpandoObject来自System。动态名称空间。

如果你不能或不想使用两个内置的JSON序列化器(JavaScriptSerializer和DataContractJsonSerializer),你可以尝试JsonExSerializer库——我在许多项目中使用它,工作得很好。

简单使用Newtonsoft。Json和Newtonsoft.Json.Linq库。

        //Create my object
        var myData = new
        {
            Host = @"sftp.myhost.gr",
            UserName = "my_username",
            Password = "my_password",
            SourceDir = "/export/zip/mypath/",
            FileName = "my_file.zip"
        };

        //Tranform it to Json object
        string jsonData = JsonConvert.SerializeObject(myData);

        //Print the Json object
        Console.WriteLine(jsonData);

        //Parse the json object
        JObject jsonObject = JObject.Parse(jsonData);

        //Print the parsed Json object
        Console.WriteLine((string)jsonObject["Host"]);
        Console.WriteLine((string)jsonObject["UserName"]);
        Console.WriteLine((string)jsonObject["Password"]);
        Console.WriteLine((string)jsonObject["SourceDir"]);
        Console.WriteLine((string)jsonObject["FileName"]);

看看http://www.codeplex.com/json/上的json-net。aspx项目。为什么要重新发明轮子?

我发现您根本不需要序列化器。如果将对象作为List返回。 让我举个例子。

在asmx中,我们使用传递的变量获取数据

// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> 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; }
}

然后使用jquery访问服务,传递该变量。

// 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);

我们得到了答案。

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