我只是使用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}]}
推荐文章
- 新建T()
- Ajax会调用什么样的响应,比如'for (;;);{json data}的意思?
- 如何将枚举绑定到WPF中的组合框控件?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- 在单元测试中设置HttpContext.Current.Session