converting list to json format - quick and easy way

后端 未结 7 1683
梦如初夏
梦如初夏 2020-12-05 09:56

Let\'s say I have an object MyObject that looks like this:

public class MyObject
{
  int ObjectID {get;set;}
  string ObjectString {get;set;}
} 
相关标签:
7条回答
  • 2020-12-05 10:05

    You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end

    0 讨论(0)
  • 2020-12-05 10:07

    I've done something like before using the JavaScript serialization class:

    using System.Web.Script.Serialization;
    

    And:

    JavaScriptSerializer jss = new JavaScriptSerializer();
    
    string output = jss.Serialize(ListOfMyObject);
    Response.Write(output);
    Response.Flush();
    Response.End();
    
    0 讨论(0)
  • 2020-12-05 10:10

    I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.

    List<MyObject> list = new List<MyObject>();
    
    Func<MyObject, JObject> objToJson =
        o => new JObject(
                new JProperty("ObjectId", o.ObjectId), 
                new JProperty("ObjectString", o.ObjectString));
    
    string result = new JObject(new JArray(list.Select(objToJson))).ToString();
    

    You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).

    0 讨论(0)
  • 2020-12-05 10:19

    For me, it worked to use Newtonsoft.Json:

    using Newtonsoft.Json;
    // ...
    var output = JsonConvert.SerializeObject(ListOfMyObject);
    
    0 讨论(0)
  • 2020-12-05 10:19

    I would avoid rolling your own and use either:

    System.Web.Script.JavascriptSerializer

    or

    JSON.net

    Both will do an excellent job :)

    0 讨论(0)
  • 2020-12-05 10:22

    why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET

    0 讨论(0)
提交回复
热议问题