How to create JSON string in C#

后端 未结 14 1006
闹比i
闹比i 2020-11-22 12:39

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the

相关标签:
14条回答
  • 2020-11-22 13:26

    Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.

            //Create my object
            var my_jsondata = new
            {
                Host = @"sftp.myhost.gr",
                UserName = "my_username",
                Password = "my_password",
                SourceDir = "/export/zip/mypath/",
                FileName = "my_file.zip"
            };
    
            //Tranform it to Json object
            string json_data = JsonConvert.SerializeObject(my_jsondata);
    
            //Print the Json object
            Console.WriteLine(json_data);
    
            //Parse the json object
            JObject json_object = JObject.Parse(json_data);
    
            //Print the parsed Json object
            Console.WriteLine((string)json_object["Host"]);
            Console.WriteLine((string)json_object["UserName"]);
            Console.WriteLine((string)json_object["Password"]);
            Console.WriteLine((string)json_object["SourceDir"]);
            Console.WriteLine((string)json_object["FileName"]);
    
    0 讨论(0)
  • 2020-11-22 13:26

    This library is very good for JSON from C#

    http://james.newtonking.com/pages/json-net.aspx

    0 讨论(0)
  • 2020-11-22 13:26

    If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:

    http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

    It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.

    0 讨论(0)
  • 2020-11-22 13:29

    If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.

    0 讨论(0)
  • 2020-11-22 13:29

    I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.

    In our asmx we get the data using the variable we passed along

    // return data
    [WebMethod(CacheDuration = 180)]
    public List<latlon> GetData(int id) 
    {
        var data = from p in db.property 
                   where p.id == id 
                   select new latlon
                   {
                       lat = p.lat,
                       lon = p.lon
    
                   };
        return data.ToList();
    }
    
    public class latlon
    {
        public string lat { get; set; }
        public string lon { get; set; }
    }
    

    Then using jquery we access the service, passing along that variable.

    // get latlon
    function getlatlon(propertyid) {
    var mydata;
    
    $.ajax({
        url: "getData.asmx/GetLatLon",
        type: "POST",
        data: "{'id': '" + propertyid + "'}",
        async: false,
        contentType: "application/json;",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //
            mydata = data;
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            console.log(xmlHttpRequest.responseText);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
    return mydata;
    }
    
    // call the function with your data
    latlondata = getlatlon(id);
    

    And we get our response.

    {"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
    
    0 讨论(0)
  • 2020-11-22 13:33

    This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.

    public static string ToJson<T>(/* this */ T value, Encoding encoding)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
    
        using (var stream = new MemoryStream())
        {
            using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
            {
                serializer.WriteObject(writer, value);
            }
    
            return encoding.GetString(stream.ToArray());
        }
    }
    
    0 讨论(0)
提交回复
热议问题