0

I'm working in C# . here I often need to convert Json that is written in C# to its regular string format, Like this C# string to

            "{" +
                     "\"grant_type\": \"password\"," +
                    "\"client_id\": 2," +
                    "\"client_secret\": \"ClientSecretHere\"," +
                    "\"username\": \"[email protected]\"," +
                    "\"password\": \"somepassword\" " +
             "}";

its regular string equivalent

  "{
      "grant_type": "password",
      "client_id": 2,
      "client_secret":"ClientSecretHere",
      "username": "[email protected]",
      "password": "somepassword"
  }"

I've searched a lot on internet but everyone is talking about the conversion from Json to C# or C# to json . Is there any good programmatic solution for this ?

8
  • 3
    Yes, it's called "serialization". Don't create JSON by concatenating strings together. Commented Apr 4, 2018 at 14:11
  • 3
    There is no such thing as "C# format JSON". The value of your string is already what you want. You need to understand how escaping works. Commented Apr 4, 2018 at 14:11
  • 2
    Why are you even creating JSON manually? What a bad idea Commented Apr 4, 2018 at 14:11
  • 1
    This doesn't make any sense whatsoever. Converting from json to C# isn't an actual thing. Json is a string. C# is a programming language. You need to edit to clarify exactly what you are trying to do. Commented Apr 4, 2018 at 14:12
  • The C# code creates a JSON formatted string that is equivalent to "it's regular string equivalent", bar the typo. Think you've misunderstood something here. What are you trying to do? Commented Apr 4, 2018 at 14:19

1 Answer 1

2

Your "c# string" is not valid. But in anycase, this could just be a bad example and the process before getting built into that "c# string" could be some sort of restriction. Anywho - let's give this a shot:

using Netwonsoft.Json.Linq;

...

var text = "{" +
                   "\"grant_type\": \"password\"," +
                   "\"client_id\": 2," +
                   "\"client_secret\": \"ClientSecretHere\"," +
                   "\"username\": \"[email protected]\"," +
                   "\"password\": \"somepassword\"
    }";

var token = JToken.Parse(text);
var json = JObject.Parse((string)token);

Console.WriteLine(json);

Should give out the "regular string equivalent" for you. If that doesn't work, maybe object deserialization will:

using Newtonsoft.Json;

...

var text = "{" +
               "\"grant_type\": \"password\"," +
               "\"client_id\": 2," +
               "\"client_secret\": \"ClientSecretHere\"," +
               "\"username\": \"[email protected]\"," +
               "\"password\": \"somepassword\"
    }";

var json = JsonConvert.DeserializeObject(text);

Console.WriteLine(json);
Sign up to request clarification or add additional context in comments.

Comments