【问题标题】:deserialize json file data in mvc在mvc中反序列化json文件数据
【发布时间】:2015-11-28 06:04:13
【问题描述】:

我的本​​地路径 sendmail.json 中有一个 json 文件,它包含这样的数据

{
"from": {
    "datatype": "String",
    "required": false
},
"subject": {
    "datatype": "String",
    "required": false
},
"text": {
    "datatype": "String",
    "required": false
},
"to": {
    "datatype": "String",
    "required": false
}

}

我想在 mvc 中反序列化这些数据,并且我想将此数据传递给 .js 角度控制器,请提供方法。

【问题讨论】:

  • 您可能想分享到目前为止您已经尝试过的内容。发帖时还要检查语法和标点符号。

标签: angularjs model-view-controller


【解决方案1】:

如果你想反序列化JSON并发送到客户端,你可以这样做。

[HttpGet]
public ActionResult mailData()
{
    List<test> myDeserializedObjList = (List<test>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List<test>));
    return Json(jsonString, JsonRequestBehavior.AllowGet);
}

希望它对你有用..!

【讨论】:

  • 什么是测试如何编写测试类
  • test 是一个模型,你可以从你的 json 数据中制作,并在 List 中使用它,如果你想制作你的 json 数据的模型,试试这个。 json2csharp.com
【解决方案2】:

无需将JSON反序列化为对象,再将对象序列化为JSON发送给浏览器。

为什么不直接将 JSON 文件发送到浏览器?

public class MailController : Controller
{
    // GET: Mail
    public ActionResult Schema()
    {
        return File(this.Server.MapPath("~/App_Data/sendmail.json"), "application/json");
    }
}

编辑:

无论如何,这里有你想要的:

public class MailController : Controller
{
    // GET: Mail
    public ActionResult Schema()
    {
        using (var reader = new StreamReader(this.Server.MapPath("~/App_Data/sendmail.json")))
        {
            var json = reader.ReadToEnd();
            var data = JsonConvert.DeserializeObject<Dictionary<string, PropertyDefinition>>(json);
            return this.Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}

public class PropertyDefinition
{
    public string datatype;
    public bool required;
}

需要Newtonsoft.JSONnuget包

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 2023-04-10
    • 2023-03-31
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多