skip to Main Content

I have a list of strings, printing out:

["TEST1","TEST2","TEST3"]

How would I go about transforming this data to this JSON formatting?

[
{
"value": "TEST1"
},
{
"value": "TEST2"
},
{
"value": "TEST3"
}
]

I do not plan on creating an object.

Have tried using dictionary and key value pairs as well.

3

Answers


  1. What about this ?

    using System;
    using System.Linq;
    using System.Text.Json;
                        
    public class Program
    {
        public static void Main()
        {
            var list = new [] {"TEST1","TEST2","TEST3" };
            var str = JsonSerializer.Serialize(list.Select(l => new { Value = l }));
            Console.WriteLine(str);
        }
    }
    
    Login or Signup to reply.
  2. you can try this

    List<string> tests = new List<string> { "TEST1", "TEST2", "TEST3"};
    
    string json = JsonConvert.SerializeObject( tests.Select( t=> new { value = t }));
    
    

    but I highly recommend to create a class

    string json = JsonConvert.SerializeObject( tests.Select( t => new Test { value = t}));
    
       // or if you are using System.Text.Json
    string json = JsonSerializer.Serialize(tests.Select(  t=>n ew Test { value = t }));
        
    public class Test
    {
        public string value {get; set;}
    }
    

    json

    [{"value":"TEST1"},{"value":"TEST2"},{"value":"TEST3"}]
    
    Login or Signup to reply.
  3. Basically the same as the others, but using a foreach:

    public static string[] TestArray = new[] { "TEST1", "TEST2", "TEST3", };
    
    public static string Test()
    {
        var data = new List<object>(TestArray.Length);
        foreach (var item in TestArray)
        {
            data.Add(new { @value = item });
        }
        var result = JsonSerializer.Serialize(data);
        return result;
    }
    

    Gives:

    [
      {
        "value": "TEST1"
      },
      {
        "value": "TEST2"
      },
      {
        "value": "TEST3"
      }
    ]
    

    It uses System.Text.Json, but it should get the same result if you use the Newtonsoft serializer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search