H
H
Heppart2021-03-19 17:07:09
JSON
Heppart, 2021-03-19 17:07:09

How to create and populate array automatically and add it to json?

It is necessary to send an array of data via api json in C#.

Request example:

string json = $"{{\\"ret\":{{\"Words\":[\"массив данных\"]}}}}";

The amount of data is always different, how to automatically create an array and write data to it?
How to substitute the entire resulting array into a json request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LiptonOlolo, 2021-03-19
@LiptonOlolo

It is not specified whether you are writing in .Net Framework or .NET Core (.NET 5), but here is a solution for .NET 5:
1. Create a Ret class with a Words property:

class Ret
{
  public Ret()
  {
    Words = new List<string>();
  }

  public List<string> Words { get; set; }
}

2. Create a class that contains the Ret class:
class RequestData
{
  public RequestData()
  {
    Ret = new Ret();
  }

  [JsonPropertyName("ret")]
  public Ret Ret { get; set; }
}

Create a RequestData object and fill it with data:
RequestData rd = new RequestData();

rd.Ret.Words.Add("Hello");
rd.Ret.Words.Add("World!");

We turn our object into a JSON string:
var json = JsonSerializer.Serialize(rd);
And print it to the console:6054c53647f1b664254765.png

B
BasiC2k, 2021-03-19
@BasiC2k

You can create a class that has a property:
Public Property Words as List(Of String)
After creating an instance of the class and populating the Words, you can serialize the class to Json. To do this, you can use JavaScriptSerializer or newtonsoft.json
The output will be json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question