1

i use the next for getting data from sql db and show it in console(for example)

DataContextDataContext ob = new DataContextDataContext();
foreach (var emp1 in ob.DimProducts)
{
    Console.WriteLine(emp1);
}

foreach (var emp2 in ob.DimProductCategories)
{
     Console.WriteLine(emp2);
}

foreach(var emp3 in ob.DimProductSubcategories)
{
    Console.WriteLine(emp3);
}

enter image description here

How i can convert data to Json ?

1
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Some RDBMS have native support for JSON - others not Commented Feb 12, 2016 at 8:33

3 Answers 3

4

You should use Json.NET library and JsonConvert.SerializeObject() for it.

DataContextDataContext ob = new DataContextDataContext();
foreach (var emp1 in ob.DimProducts)
{
    Console.WriteLine(JsonConvert.SerializeObject(emp1, Formatting.Indented));
}
foreach (var emp2 in ob.DimProductCategories)
{
     string jsonEmp2 = JsonConvert.SerializeObject(emp2, Formatting.Indented)
     Console.WriteLine(jsonEmp2);
}

There are many examples in the documentation.

You can also install Json.NET from NuGet console:

PM> Install-Package Newtonsoft.Json
Sign up to request clarification or add additional context in comments.

Comments

2

JSON Data (SQL Server) - I think you can use like this in your query Ex:

"SELECT name, surname FROM emp FOR JSON AUTO"

Result will be like this :

    [ 
   { "name": "John" },
   { "name": "Jane", "surname": "Doe" }
]

Another example query is

  SELECT * FROM OPENJSON(@json, N'lax $.info')

1 Comment

You need SQL Server 2016 for this though.
1

If you're using Azure or Sql Server 2016 you can get JSON directly from the sql server by adding FOR JSON PATH to the end of your SQL query.

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.