【问题标题】:How can I serialize my data using Json.net?如何使用 Json.net 序列化我的数据?
【发布时间】:2015-04-29 16:56:30
【问题描述】:

我想将我的数据转换为 json。我也想使用 JSON.NET,因为我正在研究 ASP.net MVC。我已经关注了Error during serialization using the JSON JavaScriptSerializer.Fastest JSON Serializer for .NET released 这两个链接,但我还不能这样做。 我有一个调用类方法的动作。此方法必须返回 JSON。所以首先要怎么序列化数据,应该是什么类型的return。这是我的代码 sn-p 先是动作,然后是 Json 类和方法。

最重要的是我不希望 Json 作为字符串,因为我希望能够使用“。”访问其中的字段。

public ActionResult HighChartAction(int id)
{
   JsonModel j = new JsonModel();
   ??? chartData = j.GetMessagesforChart(id); // What should be the type of chartData for JSON data
}
----------------------    
public class JsonModel
{
    public JsonResult GetMessagesforChart(int id)
    {
          DataRepository _messageRepository = new DataRepository();
          var gluc = _messageRepository.GetAllMessages(id);
          var json = JsonConvert.SerializeObject(gluc); // THIS IS A STRING
          return json; // ERROR BECAUSE I WANT IT A JSONRESULT NOT STRING
     }
}

---------------------
    namespace MonitorUI.Models
    {
        public class DataBase
        {
            public int id { get; set; }

            public DateTime date_time { get; set; }

            public int my_value{ get; set; }
        }
    }

所以 var gluc 的类型是 IEnumerable(DataBase)


相关的后续问题:How to fill database list in series and xAxis objects of HighChart

请帮忙

【问题讨论】:

  • 如果您想使用“.”访问字段,您需要一个模型类,其中包含您想要包含在 JSON 中的属性。
  • @user2217303 提供更多提示源来帮助您。
  • 您真正想要返回什么? JSON 还是 JsonResult 对象?而gluc返回的是什么类型?
  • @HarveySpecter 我有一个,我会在一秒钟内发布更多详细信息。

标签: c# serialization json.net


【解决方案1】:

你的功能:

public JsonResult GetMessagesforChart(int id)
{
      DataRepository _messageRepository = new DataRepository();
      var gluc = _messageRepository.GetAllMessages(id);
      var json = JsonConvert.SerializeObject(gluc); // THIS IS A STRING
      return json; // ERROR BECAUSE I WANT IT A JSONRESULT NOT STRING
 }

使用此功能更新:

public JsonResult GetMessagesforChart(int id)
{
      DataRepository _messageRepository = new DataRepository();
      DataBase gluc = _messageRepository.GetAllMessages(id);
      return JsonConvert.SerializeObject(gluc);
 }

【讨论】:

    【解决方案2】:

    要返回 JsonResult,您可以像这样简单地用 Json() 包装对象

    public JsonResult GetMessagesforChart(int id)
    {
        DataRepository _messageRepository = new DataRepository();
        var gluc = _messageRepository.GetAllMessages(id);
        return Json(gluc);
    }
    

    Json是关于序列化的,所以这里的格式是字符串,如果需要用“.”访问字段,需要反序列化为对象

    【讨论】:

    • 但是我已经将它作为对象检查,请检查我的 gluc 变量类型的更新。如果是这种情况,那么 Json 有什么好处?我的目标是以 json 的形式获取数据,然后添加到 highchart
    • json 主要用于 ajax 调用,或者受 api 约束。如果只需要将模型从控制器传递到视图,则不需要 json,可以传递 ienumerable
    • 我使用了 ienumerable 类型并将其转换为列表。有一个分配硬编码值的代码,我想用我的列表/数组替换它们。它不起作用..我将把代码放在问题的末尾。请帮助@uowzd01
    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多