get input from user and turn it into json in csharp

To get input from a user and turn it into JSON format in C#, you can use the Newtonsoft.Json library. Here's an example:

main.cs
using Newtonsoft.Json;
using System;

class Program
{
    static void Main()
    {
        // Get input from user
        Console.WriteLine("Enter a name:");
        string name = Console.ReadLine();

        Console.WriteLine("Enter an age:");
        int age = Convert.ToInt32(Console.ReadLine());

        // Create an object to serialize
        var obj = new { Name = name, Age = age };

        // Serialize the object to JSON
        string json = JsonConvert.SerializeObject(obj);

        Console.WriteLine(json);
    }
}
531 chars
24 lines

In the example above, we use the Console.ReadLine() method to get input from the user for the name and age fields. We then create an object with those values and use the JsonConvert.SerializeObject() method to serialize the object to JSON format.

To deserialize JSON input from a user, you can use the JsonConvert.DeserializeObject() method:

main.cs
using Newtonsoft.Json;
using System;

class Program
{
    static void Main()
    {
        // Get input from user
        Console.WriteLine("Enter JSON:");
        string json = Console.ReadLine();

        // Deserialize the JSON to an object
        var obj = JsonConvert.DeserializeObject(json);

        Console.WriteLine("Name: " + obj["Name"]);
        Console.WriteLine("Age: " + obj["Age"]);
    }
}
408 chars
19 lines

In the example above, we use the Console.ReadLine() method to get input from the user for the JSON string. We then use the JsonConvert.DeserializeObject() method to deserialize the JSON string to an object. We can then access the fields of the object using the indexer ([]) operator.

gistlibby LogSnag