将数组解析为 json 的问题
我的问题: 我正在编写一个网络应用程序来管理联系人。在服务器端,我正在使用 Razor 语法 (C#),并且使用 json 编码字符串作为标头向我的服务器发送 ajax 请求。 test.cshtml 收到的信息如下:
var j = Json.Decode(Request["json"]);
现在我可以完美地使用所有对象。但!我在 json 编码字符串中有一个数组,例如 ...,"persons":[1,2,3],...
Json.Decode 将其解码为一个数组,它应该是我的可以用来将数据写入我的数据库。完成此操作后,我想使用以下方法将更新后的对象发送回客户端(数组尚未更改或执行任何其他操作):
<text>
@Html.Raw(Json.Encode(j));
@j.persons.Length;
</text>
并且 person 元素的输出为 ...,"persons" :{},...
,但 Person 的长度应该是 3。我做错了什么?是否有参数告诉 Json.Encode 对子对象和数组进行编码?
感谢您的支持
PS:@j.persons.Length只是为了证明数组不为空且存在
My problem:
I'm writing a web app to manage contacts. On the server side, i'm working with Razor Syntax (C#) and i'm sending ajax requests to my server with a json encoded string as header. The test.cshtml recieves this as follows:
var j = Json.Decode(Request["json"]);
Now i can use all the objects perfectly fine. BUT! I have an array in the json encoded string like...,"persons":[1,2,3],...
The Json.Decode decodes this as it should to an array which i can use to write data to my database. After doing this, i'd like to send the updated object back to the client (the array has not been altered or done anything else with) using:
<text>
@Html.Raw(Json.Encode(j));
@j.persons.Length;
</text>
and the output of the persons element is ...,"persons":{},...
, but the length of persons is 3 as it should be. What am I doing wrong? Are there parameters to tell Json.Encode to encode sub-objects and arrays as well?
Thank you for your support
PS: @j.persons.Length is just to prove the array is not empty and existing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现了问题。我必须用循环强类型自动生成的数组(来自 Json.Decode):
谢谢你的方法 Joseph
I found the problem. I had to strongly type the automatically generated array (from Json.Decode) with a loop:
Thank you for your approach Joseph
因为它只编码根而不是人尝试
j.as_json(:include => :persons)
because it's only encoding the root and not persons try
j.as_json(:include => :persons)