Home > Software engineering >  C# serializing JSON data from Database for API
C# serializing JSON data from Database for API

Time:01-05

My goal is to get the data from the database, serializing them into JSON format and send it to the API. The problem is that I don't know how to get right JSON format for the API.

C# Worker service collecting data from database.

from database i got:

1|John|Wick|Action|101

my API needs this JSON:

{ 
     "Name":"John",
     "Surname":"Wick",
     "Type":"Action",
     "Length":"101"
}

when i use in C# serializing to JSON:

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(values);

i got:

[John,Wick,Action,101]

is there any way how to add name of values to JSON ?

CodePudding user response:

First split the database result based on the delimiter

string dbResult = ...;  //1|John|Wick|Action|101
string[] dbResults = dbResult.Split("|");

Second create an anonymous object (if you don't want to introduce a data model class/struct/record)

var result = new 
{
  Name = dbResults[0],
  Surname = dbResults[1],
  Type = dbResults[2],
  Length = dbResults[3],
};

Third serialize the anonymous object

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(result);
  •  Tags:  
  • Related