将JSON反序列化为C#

编程入门 行业动态 更新时间:2024-10-24 04:30:23
将JSON反序列化为C# - 来自复选框的值(Deserialize JSON to C# - Values from Checkboxes)

我试图通过AJAX将表单值发送到C#Web服务。 然后,使用JavaScriptSerializer.Deserialize,将JSON转换为C#类。 以下是课程:

[Serializable] [DataContract(Name = "PostParameters")] public class TagData { public TagData() { } [DataMember(Name = "TargetId")] public string TargetId { get; set; } [DataMember(Name = "TargetType")] public string TargetType { get; set; } [DataMember(Name = "Tags")] public List<string> Tags { get; set; } }

这里是被调用的方法:

[WebMethod] public string UpdateTags(string PostParameters) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var tagData = serializer.Deserialize<TagData>(PostParameters); }

这适用于多个复选框被选中的情况。 标签属性已成功填充。 但是,如果检查少于两个项目,则会出现转换错误。 序列化程序不能将单个字符串值转换为List对象。

以下是选中复选框发送JSON的方式: {"Tags":"14","TargetId":"36946","TargetType":"Officer"}

这里是JSON发送时如何选中多个复选框: {"Tags":["12","5","2"],"TargetId":"36946","TargetType":"Officer"}

我试图将我的C#类中的Tags属性更改为一个字符串数组: public string[] Tags { get; set; } public string[] Tags { get; set; } public string[] Tags { get; set; }然而,这导致JSON根本没有被映射。

我也尝试添加[]到复选框输入名称,如下所示: <input type="checkbox" name="tags[]" />

这样就发送了JSON,并选中了一个复选框: {"Tags[0]":"14","TargetId":"36946","TargetType":"Officer"}

并检查了多个复选框: {"Tags[0]":"14","Tags[1]":"19","TargetId":"36946","TargetType":"Officer"}

这看起来好像可以和字符串数组一起使用,但它不会映射到那个或List属性。 Tags属性将始终为空,因为它无法映射。

更新 - 这是JSON生成的地方

var params = $.toJSON({ 'PostParameters': JSON.stringify($inputs.serializeObject()) });

这里是serializeObject()函数:

serializeObject: function () { var obj = {}, names = {}; $.each(this.serializeArray(), function (i, o) { var n = o.name, v = o.value; if (n.includes('[]')) { names.n = !names.n ? 1 : names.n + 1; var indx = names.n - 1; n = n.replace('[]', '[' + indx + ']'); } obj[n] = obj[n] === undefined ? v : $.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v]; }); return obj; }

任何帮助表示赞赏。

I'm attempting to send form values over AJAX to a C# web service. Then, using JavaScriptSerializer.Deserialize, convert the JSON to a C# class. Below is the class:

[Serializable] [DataContract(Name = "PostParameters")] public class TagData { public TagData() { } [DataMember(Name = "TargetId")] public string TargetId { get; set; } [DataMember(Name = "TargetType")] public string TargetType { get; set; } [DataMember(Name = "Tags")] public List<string> Tags { get; set; } }

Here is the method being called:

[WebMethod] public string UpdateTags(string PostParameters) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var tagData = serializer.Deserialize<TagData>(PostParameters); }

This works when more than one checkbox is checked. The Tags property is successfully populated. However, when less than two items are checked, there is a conversion error. The serializer cannot convert the single string value to a List object.

Here is how the JSON is sent with one checkbox checked: {"Tags":"14","TargetId":"36946","TargetType":"Officer"}

Here is how the JSON is sent with more than one checkbox checked: {"Tags":["12","5","2"],"TargetId":"36946","TargetType":"Officer"}

I attempted changing the Tags property in my C# class to a string array: public string[] Tags { get; set; } however, this resulted in the JSON not being mapped at all.

I also attempted adding [] to the checkbox input names like so: <input type="checkbox" name="tags[]" />

This sent the JSON across as so, with one checkbox checked: {"Tags[0]":"14","TargetId":"36946","TargetType":"Officer"}

and more than one checkboxes checked: {"Tags[0]":"14","Tags[1]":"19","TargetId":"36946","TargetType":"Officer"}

This seems like it would work with the string array property, but it won't map for either that or the List property. The Tags property will always be null because it's unable to map.

UPDATE - Here's where the JSON is generated

var params = $.toJSON({ 'PostParameters': JSON.stringify($inputs.serializeObject()) });

and here's the serializeObject() function:

serializeObject: function () { var obj = {}, names = {}; $.each(this.serializeArray(), function (i, o) { var n = o.name, v = o.value; if (n.includes('[]')) { names.n = !names.n ? 1 : names.n + 1; var indx = names.n - 1; n = n.replace('[]', '[' + indx + ']'); } obj[n] = obj[n] === undefined ? v : $.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v]; }); return obj; }

Any help is appreciated.

最满意答案

编辑你的客户端代码来发送一个元素的数组,以防止一个复选框被选中 选中一个复选框的JSON: {"Tags":["14"],"TargetId":"36946","TargetType":"Officer"}

I was able to solve this using Rick Strahl's example here: https://weblog.west-wind.com/posts/2010/Sep/07/Using-jQuery-to-POST-Form-Data-to-an-ASPNET-ASMX-AJAX-Web-Service

Essentially, create a NameValue class:

public class NameValue { public string name { get; set; } public string value { get; set; } }

Use these extension methods to get form values from the collection:

public static class NameValueExtensionMethods { /// <summary> /// Retrieves a single form variable from the list of /// form variables stored /// </summary> /// <param name="formVars"></param> /// <param name="name">formvar to retrieve</param> /// <returns>value or string.Empty if not found</returns> public static string Form(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).FirstOrDefault(); if (matches != null) return matches.value; return string.Empty; } /// <summary> /// Retrieves multiple selection form variables from the list of /// form variables stored. /// </summary> /// <param name="formVars"></param> /// <param name="name">The name of the form var to retrieve</param> /// <returns>values as string[] or null if no match is found</returns> public static string[] FormMultiple(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).Select(nv => nv.value).ToArray(); if (matches.Length == 0) return null; return matches; } }

Post the data using JSON.stringify only:

data: JSON.stringify({ formVars: arForm })

and accepting a parameter to my web method as a NameValue array:

public string UpdatTags(NameValue[] formVars)

This works when multiple checkboxes are checked, a single checkbox is checked, or no checkboxes are checked.

更多推荐

本文发布于:2023-07-15 19:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!