-2

Apologies if this seems basic, but I have the following json

  {
    "id": "71e590d2-ab61-47ae-9ada-b9cedbf309bc",
    "user_firstname": "Tommy",
    "user_lastname": "Tester",
    "user_displayname": "Tommy Tester",
    "user_primary_email": "tommy@tester.com"
  }

I just want to convert this to a string in a C# function that is accepted by our system so

"{\"id\":\"71e590d2-ab61-47ae-9ada-b9cedbf309bc\",\"user_firstname\":\"Tommy\",\"user_lastname\":\"Tester\",\"user_displayname\":\"Tommy Tester\",\"user_primary_email\":\"tommy@tester.com\"}"

I can do it manually using this online tool https://tools.knowledgewalls.com/jsontostring

RShome
  • 489
  • 2
  • 11
  • 35
  • Thanks, it is just some sample json, but I need to convert it to a string so it can be stored as a string in our database – RShome Oct 16 '20 at 12:23
  • 2
    Do not store data at your DB in JSON format. JSON is a format made for data interchange. If you do that, you won't be able to easily retrieve the information about the user from the database once stored. I'd suggest to deserialize the object into a data structure and store the data into separated database fields. – ɐsɹǝʌ ǝɔıʌ Oct 16 '20 at 12:46
  • 1
    Any JSON serializer can serialize a JSON string to JSON, thereby creating double-serialized data. See e.g. [How do I turn a C# object into a JSON string in .NET?](https://stackoverflow.com/q/6201529/3744182). [tag:json.net] as mentioned below is one such serializer. – dbc Oct 18 '20 at 23:35

1 Answers1

2

I'd suggest you to use JSON library from Newtonsoft. You can install the library from NuGet Packet Manager.

Once installed you can convert your JSON object into a string just in one line by using the JsonConvert.ToString method.

string myString = JsonConvert.ToString(yourJsonObject);
ɐsɹǝʌ ǝɔıʌ
  • 4,440
  • 3
  • 35
  • 56