gpt4 book ai didi

javascript - 使用 Jquery/Javascript 读取 NewtonSoft Json 数据

转载 作者:行者123 更新时间:2023-11-28 06:58:44 25 4
gpt4 key购买 nike

我在使用从 Controller 发送的对象来使用 Json 进行查看时遇到问题。

我使用 NewtonSoft.Json 7.x.x 将列表序列化为 Json,将对象列表发送到 View 。我正在使用以下代码进行序列化:

return JsonConvert.SerializeObject(DataToSend, Formatting.None, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

我有 2 个实体类:1)表格2) 表单字段

这两个实体之间存在一对多关系。

public class Form
{
public long ID { get; set; }
public string Name { get; set; }
public virtual List<FormField> FormFields { get; set; }
}

public class FormField
{
public long FormID { get; set; }
public string FieldLabel { get; set; }
public string FieldType { get; set; }
public string FieldValue { get; set; }
public virtual Form form { get; set; }
}

我正在尝试将 FormField 列表发送到 View 以使用 Javascript 进行渲染。我可以使用上面的序列化方法发送它。

但问题是,当我收到 Javascript 中的对象数组时。它具有 Json 引用对象 ID。我无法正常访问这些对象。

我能够渲染该数组中的第一个 FormField 值,但无法渲染其余的值。它以未定义的形式出现。

我附上了我在 UI 上收到的 JSON 对象值的屏幕截图。可以看到有一个Object数组。每个对象都应该具有 FormField 类型的对象,并且应该具有该字段的值,但没有。

只有索引 0 处的对象具有值,其余索引仅具有引用 ID。

Json Object Values

请帮我解决这个问题。

谢谢

最佳答案

我不知道这是否是最好的解决方案,但我发帖是为了避免其他人寻找解决方案的麻烦。

我设法使用 .NET 扩展库插件来做到这一点。我没有使用 Newtonsoft.Json,而是使用 System.Web.Extension DLL。

我将属性ScriptIgnore放入我的模型中:

public class Form
{
public long ID { get; set; }
public string Name { get; set; }

[ScriptIgnore]
public virtual List<FormField> FormFields { get; set; }
}

public class FormField
{
public long FormID { get; set; }
public string FieldLabel { get; set; }
public string FieldType { get; set; }
public string FieldValue { get; set; }

[ScriptIgnore]
public virtual Form form { get; set; }
}

然后,我使用 System.Web.Script.Serialization.JavaScriptSerializer 将其序列化为:

return new JavaScriptSerializer().Serialize(DataToSend);

它将序列化所有数据,但会忽略具有 ScriptIgnore 属性的属性,并且不会尝试序列化它们。对我来说,它按要求工作了。

刚刚了解到 NewtonSoft.Json 提供的属性 JsonIgnoreScriptIgnore 执行相同的工作。因此,如果您正在使用 NewtonSoft 库,那么您也可以使用它。

很高兴知道有更多方法可以实现相同的结果;)

关于javascript - 使用 Jquery/Javascript 读取 NewtonSoft Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com