简体   繁体   中英

C# List<string> to JSON objects

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM