I have classes like these:
class MyDate { int year, month, day; } class Lad { string firstName; string lastName; MyDate dateOfBirth; }
And I would like to turn a Lad
object into a JSON string like this:
{ "firstName":"Markoff", "lastName":"Chaney", "dateOfBirth": { "year":"1901", "month":"4", "day":"30" } }
(Without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files.
Are there other options besides manually creating a JSON string writer?
How to Turn on an Air Conditioner. Once you've examined your cooling system and changed your air filter, you may be wondering how you actually turn on your air conditioner. For most central air systems, the process is simple. Simply move the switch on your thermostat from “Heat” to “Cool”.
The standard practice is to position these vents so that one can't see through them to the ducting beyond. So, return vents closer to the ground should be oriented pointing downward. Conversely, return vents closer to the ceiling should be oriented pointing upward.
Since we all love one-liners
... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
Documentation: Serializing and Deserializing JSON
Microsoft recommends that you DO NOT USE JavaScriptSerializer
See the header of the documentation page:
For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.
You could use the JavaScriptSerializer
class (add reference to System.Web.Extensions
):
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
A full example:
using System; using System.Web.Script.Serialization; public class MyDate { public int year; public int month; public int day; } public class Lad { public string firstName; public string lastName; public MyDate dateOfBirth; } class Program { static void Main() { var obj = new Lad { firstName = "Markoff", lastName = "Chaney", dateOfBirth = new MyDate { year = 1901, month = 4, day = 30 } }; var json = new JavaScriptSerializer().Serialize(obj); Console.WriteLine(json); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With