Generate lightweight JSON using DataContractJsonSerializer

后端 未结 2 957
没有蜡笔的小新
没有蜡笔的小新 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}
    

提交回复
热议问题