Generate lightweight JSON using DataContractJsonSerializer

后端 未结 2 930
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 19:50

I\'m trying to generate JSON using C# and DataContractJsonSerializer in .Net 3.5. The problem is that I can\'t figure out how to build the structure correct for the result I

相关标签:
2条回答
  • 2021-01-14 20:35

    You should look at using the JavaScriptSerializer. It's part of the .NET framework (distributed in System.Web.Extensions). To get the result you want you can do this:

    var results = new[]
    {
        new{id=1,name="Result 1"},
        new{id=2,name="Result 2"},
        new{id=3,name="Result 3"}
    };
    
    var js = new JavaScriptSerializer();
    var result = js.Serialize(new
    {
        status = "ok",
        response = results,
        caller = 1135345
    });
    

    You can either use anonymous classes, or any existing ones. Works perfectly fine :) The return value of this call would be:

    {"status":"ok","response":[{"id":1,"name":"Result 1"},{"id":2,"name":"Result 2"},{"id":3,"name":"Result 3"}],"caller":1135345}
    
    0 讨论(0)
  • 2021-01-14 20:38

    Using the JavaScriptSerializer rather than DataContractJsonSerializer on a Dictionary will remove the Key/Value json attributes and make them into a "keyed" array.

    http://msdn.microsoft.com/en-us/library/bb412168.aspx

    Have you attributed your classes with the [DataContract] and [DataMember] decorators?

    http://msdn.microsoft.com/en-us/library/bb412179.aspx

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