Home > front end >  How to use string.Format with curly brackets
How to use string.Format with curly brackets

Time:11-30

I want to create a json string that contains a list of long values with the following structure: {"document_ids":[23461504,20639162,20395579]}

I solved the problem with the line below, but I feel like I could do it with a cleaner command(string.Format).

var json = "{\"document_ids\":"   JsonConvert.SerializeObject(My List<long>)   "}";

But the command I write with string.Format gives an error message.

var json = string.Format("{\"document_ids\":{0}}", JsonConvert.SerializeObject(My List<long>));

I get this error message. System.FormatException: 'Input string was not in a correct format.'

CodePudding user response:

Do not manually assemble json strings. There are already useful classes that make the most work for you. Just use the System.Text.Json.JsonSerializer class for example.

A full working example would be this:

internal class Program
{
    static void Main( string[] args )
    {
        var myData = new MyData()
        {
            MyListOfLongs = new List<long>() { 23461504, 20639162, 20395579 }
        };

        var jsonString = JsonSerializer.Serialize( myData, new JsonSerializerOptions() { WriteIndented = true } );
    }
}

public class MyData
{
    [JsonPropertyName( "document_ids" )]
    public List<long> MyListOfLongs
    { get; set; }
}

The variable jsonString contains your desired json string ^^

If you like to deserialize the string again, take a look at the class System.Text.Json.JsonSerializer again ... it contains also a Deserialize method.

CodePudding user response:

You can serialize an anonymous object having such a document_ids property.

var numbers = new List<long> { 23461504, 20639162, 20395579 };

var json = JsonConvert.SerializeObject(
    new
    {
        document_ids = numbers
    });
  • Related