Create nested json with c#

前端 未结 4 2003
日久生厌
日久生厌 2021-02-09 14:56

I am able to create a flat serialized JSON string pretty easily with c#

My issue is I want to create a nested string like this below

[ { 
    title: \"Y         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 15:26

    Try using

    using System.Web.Script.Serialization;
    
    //Assumed code to connect to a DB and get data out using a Reader goes here
    
    Object data = new {
        a = reader.GetString(field1),
        b = reader.GetString(field2),
        c = reader.GetString(field3)
    };
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    string json = javaScriptSerializer.Serialize(data);
    

    This is built-in and saves you the work of serializing to JSON yourself!

    This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.

提交回复
热议问题