-3

I have a string in ASP.NET webpage and I want to convert it into list and then convert it into JSON, string had \n characters in it I wanted to remove them so I used following code:

str.Split(new char[] { '\n'}).ToList();

But when I checked my exported JSON it looked as below:

{
  "train_statusresult": [
    "Label",
    "",
    "",
    "#",
    "Station",
    "Day",

and before I performed split, I looked like this:

{
  "train_statusresult": [
    "Label\n\n\n#\nStation",
    "\nDay\n

I want to remove "" quotes which don't have any character between them and want to make JSON well structured. Please help me out.

12
  • 2
    "but it is giving me error as \ and n are two characters" - what error? That code should compile fine.
    – Jon Skeet
    Jul 25, 2015 at 19:45
  • @JonSkeet I want to delete "/n" and eliminate the white space but I'm not able to do so.
    – ts092
    Jul 25, 2015 at 19:46
  • '\n' is a single character. Jul 25, 2015 at 19:46
  • @ts092: Backslash and n are to characters, but the code you've got is using \n as a character literal, representing the single character U+000A, which I assumed is the character you want to split. And you still haven't said what error you're getting. It you genuinely have a backslash and an n in your text, you might want to split via a regex. It's not clear what the string really is though... if you're only observing the \n in the debugger, that's almost certainly just the newline character being escaped by the debugger. We don't have enough information to help you.
    – Jon Skeet
    Jul 25, 2015 at 19:48
  • @ts092: try this str.Split(new string[] { "\n" }).ToList();
    – walruz
    Jul 25, 2015 at 19:49

1 Answer 1

0

I am not sure if I understand your question but to split the string and remove the spaces you can use the options:

        string MyString = "train_statusresult \n "+Environment.NewLine+" # Station Day";
        var dtList = MyString.Split(new string[] { Environment.NewLine, "\n", " " }, 
            StringSplitOptions.RemoveEmptyEntries);

RemoveEmptyEntries will do what its names says. If you want the string separated by blank spaces you can add the " " in the list of separators, or you can remove them if you want. Then you can convert it in to JSON and I think the problem would be solved.

Regards!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.