Skip to content

Latest commit

 

History

History
67 lines (56 loc) · 1.55 KB

FromObject.md

File metadata and controls

67 lines (56 loc) · 1.55 KB

Create JSON from an Object

This sample converts .NET values to LINQ to JSON using Argon.JToken.FromObject(System.Object).

public class Computer
{
    public string Cpu { get; set; }
    public int Memory { get; set; }
    public IList<string> Drives { get; set; }
}

snippet source | anchor

var i = (JValue) JToken.FromObject(12345);

Console.WriteLine(i.Type);
// Integer
Console.WriteLine(i.ToString());
// 12345

var s = (JValue) JToken.FromObject("A string");

Console.WriteLine(s.Type);
// String
Console.WriteLine(s.ToString());
// A string

var computer = new Computer
{
    Cpu = "Intel",
    Memory = 32,
    Drives = new List<string>
    {
        "DVD",
        "SSD"
    }
};

var o = (JObject) JToken.FromObject(computer);

Console.WriteLine(o.ToString());
// {
//   "Cpu": "Intel",
//   "Memory": 32,
//   "Drives": [
//     "DVD",
//     "SSD"
//   ]
// }

var a = (JArray) JToken.FromObject(computer.Drives);

Console.WriteLine(a.ToString());
// [
//   "DVD",
//   "SSD"
// ]

snippet source | anchor