1

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 ?

2
  • 1
    You need a class, create an instance of it with the values loaded from the database (this could be done by an ORM like Dapper or EF) and then serialize with the overload that takes the type. Like SerializeObject<ClassType>(classInstance) Commented Jan 4, 2022 at 13:40
  • You meant to write serializing, not parsing. Parsing is the act of converting a string into an object, serializing is the inverse of that. I updated your question for you. Commented Jan 4, 2022 at 13:42

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.