如何在c#中反序列化JSON数据并从中获取值
本文关键字:获取 数据 反序列化 JSON | 更新日期: 2023-09-27 18:06:09
我已经序列化了mvc表单,现在想在c#中反序列化它。请帮我解决这个问题。以下是我的前端代码
<input type="search" id="txtsearch">
<input type="button" id="btnsearch" />
<script type="text/javascript">
$(function () {
DrawTable(0);
$('#btnsearch').click(function (e) {
var searchname = $('#txtsearch').val();
var form = $('form').serialize();
//var form = $(this).serializeArray();
DrawTable(form);
});
</script>
,下面是我想通过反序列化
从序列化数据中获取值的方法public JsonResult GetAllCustomers(string sEcho, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0, string filters, int UserId = 0,string form="") {
string sortDirection = sSortDir_0;
DataTableGridModel resultModel = new Logic(x,y ).GetCustomersForGrid(sEcho, sColumns, iDisplayStart, iDisplayLength, sSearch, iSortCol_0, sSortDir_0, UserId);
return Json(resultModel, JsonRequestBehavior.AllowGet);
}
使用Newtonsoft.Json.dll在c#中序列化和反序列化json数据
使用Newtonsoft.Json.dll创建以下方法,并通过传递字符串格式的json数据调用反序列化方法
private static JsonSerializerSettings CreateSettings()
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
return settings;
}
private static Newtonsoft.Json.JsonSerializer CreateSerializer()
{
var settings = CreateSettings();
return Newtonsoft.Json.JsonSerializer.Create(settings);
}
public T Deserialize<T>(object target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
var result = default(T);
var json = target as string;
if (json != null)
{
var serializer = CreateSerializer();
using (var stringReader = new StringReader(json))
{
using (JsonReader jsonReader = new JsonTextReader(stringReader))
{
result = serializer.Deserialize<T>(jsonReader);
}
}
}
return result;
}
1)。在客户端将表单编码为JSON字符串
//in javascript, serialize the form to JSON:
// -- this will only work if all elements on the form have a name attribute -
var stringToReturnToServer = JSON.stringify($('form').serializeArray());
2)。解码json字符串到字典,所以你可以检索元素的名称在服务器端,您将处理一个包含JSON对象数组的字符串,每个对象数组都有两个属性:名称和值。这很好地转化为c# Dictionary<string,string>
using Newtonsoft.Json;
private class FormField
{
[JsonProperty("name")]
public string a { get; set; }
[JsonProperty("value")]
public string b { get; set; }
}
private void ReadFormData(string sFormData)
{
//this will throw if you give two form fields the same name in your HTML.
Dictionary<string,string> asFormData = JsonConvert.DeserializeObject<List<FormField>>(sFormData).ToDictionary(x => x.a, x => x.b);
//VALUES OF FORM ELEMENTS NOW ACCESSIBLE BY NAME IN DICTIONARY
string sSearchText = asFormData["txtsearch"];
}
…这里的代码仅限于序列化和反序列化,您需要将实际的JSON字符串GET或POST回服务器。