user2217303
user2217303

Reputation: 356

How can I serialize my data using Json.net?

I want to convert my data to json. I aslo want to use JSON.NET, for I am working on ASP.net MVC. I have followed those two links Error during serialization using the JSON JavaScriptSerializer. and Fastest JSON Serializer for .NET released, but I am not able yet to do it. I have an action which calls a method of a class. This method must return the 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.

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 "."

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)


Related continuing question here: How to fill database list in series and xAxis objects of HighChart

Help Please

Upvotes: 0

Views: 247

Answers (2)

Krunal Mevada
Krunal Mevada

Reputation: 1655

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);
 }

Upvotes: 1

uowzd01
uowzd01

Reputation: 1000

To return JsonResult you can simply wrap the object with Json() like so

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

Upvotes: 0

Related Questions