user3768730
user3768730

Reputation: 29

Receiving json string database MS SQL database, formatting problem

I run a C# app, which gets json from MS SQL 2016 using a stored procedure.

string t = da.ExecuteScalar().ToString();

I get strangely formatted json:

"{\"Komponent\":\"00066X96A\",\"Opis\":\"Part2 II F P\\/L S!\\\"31\\\"\",\"Jednos\":\"szt\",\"Enabled\":true,\"Powierzchnia\":0.0070,\" ... SQLcommand added escaped char. 

My stored procedure generates clear json from Management Studio, but the C# app adds strange characters.

In C# I execute scalar:

SqlConnection  conn2 = new SqlConnection(builder2.ConnectionString);
conn2.Open();
SqlCommand da = new SqlCommand("[dbo].[R1079]", conn2 );
da.CommandType = CommandType.StoredProcedure;
string t = da.ExecuteScalar().ToString();

This also happens when sent as response in MVC app, not only debugging mode:

public JsonResult Test(int id)
    {
        SqlConnectionStringBuilder builder2 = new qlConnectionStringBuilder();
        builder2.ConnectionString= "Data Source=cz1-dbs\\BER;Initial Catalog=BER;Integrated Security=True;Application Name=Rapor.exe";


        SqlConnection  conn2 = new SqlConnection(builder2.ConnectionString);

        conn2.Open();

        SqlCommand da = new SqlCommand("[dbo].[R1079]", conn2 );

        da.CommandType = CommandType.StoredProcedure;
        string t = da.ExecuteScalar().ToString();

        return Json(t, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);

    }

Upvotes: 0

Views: 394

Answers (1)

Fabian Claasen
Fabian Claasen

Reputation: 284

You make a string from the result with the ToString method. The 'weird' characters in your string are escaped characters.

You can serialize and deserialize json with the NuGet package Newtonsoft.Json. For example:

JsonConvert.SerializeObject(someobject);

This will generate a json string from the object you pass in.

JsonConvert.DeserializeObject<SomeObject>(jsonString);

This will generate an object of Type SomeObject from the jsonString you pass in.

Hope this helps you!

Upvotes: 1

Related Questions