[英]How can I serialize my data using Json.net?
I want to convert my data to json. 我想将数据转换为json。 I aslo want to use JSON.NET, for I am working on ASP.net MVC. 我也想使用JSON.NET,因为我正在使用ASP.net MVC。 I have followed those two links Error during serialization using the JSON JavaScriptSerializer. 我在使用JSON JavaScriptSerializer进行序列化时遵循了这两个链接错误。 and Fastest JSON Serializer for .NET released , but I am not able yet to do it. 并发布了适用于.NET的最快的JSON序列化程序 ,但我还无法做到这一点。 I have an action which calls a method of a class. 我有一个调用类方法的操作。 This method must return the JSON. 此方法必须返回JSON。 So first of all how to serialize the data and what type of return should it be. 因此,首先如何序列化数据以及应该返回哪种类型的数据。 This is my code snippet for the action first then the Json class and method. 这是我的动作的代码片段,然后是Json类和方法。
Most Importantly is that I don't want the Json as a string because I want to be able to access the fields in it using the "." 最重要的是,我不想将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; }
}
}
so var gluc is of type IEnumerable(DataBase) 因此var gluc的类型为IEnumerable(DataBase)
Related continuing question here: How to fill database list in series and xAxis objects of HighChart 这里相关的继续存在的问题: 如何在HighChart的系列和xAxis对象中填充数据库列表
Help Please 请帮助
Your function : 您的职能:
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
}
Update with this function : 使用此功能更新:
public JsonResult GetMessagesforChart(int id)
{
DataRepository _messageRepository = new DataRepository();
DataBase gluc = _messageRepository.GetAllMessages(id);
return JsonConvert.SerializeObject(gluc);
}
To return JsonResult you can simply wrap the object with Json() like so 要返回JsonResult,您可以像这样简单地用Json()包装对象
public JsonResult GetMessagesforChart(int id)
{
DataRepository _messageRepository = new DataRepository();
var gluc = _messageRepository.GetAllMessages(id);
return Json(gluc);
}
Json is about serialization so the format here is string, if you need to access field with ".", you need to deserialize it to object Json与序列化有关,因此此处的格式为字符串,如果您需要使用“。”访问字段,则需要将其反序列化为对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.