Home > Mobile >  C# List<string> to JSON objects
C# List<string> to JSON objects

Time:01-17

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.

CodePudding user response:

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);
    }
}

CodePudding user response:

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"}]

CodePudding user response:

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.

  • Related