How to remove space from the JSON (String) value in C#?

Asked

Viewed 341 times

1

I have the following JSON stored in a String variable:

{"novosPedidos":[],"pedidos":[{"Apagar":" 633.56"}]}

The "Delete" value contains a space which I need to remove.

I tried using the Replace() method but did not get the expected result:

var newJson = json.Replace(":\" ", ":\"");

The newJson "Delete" value remained unchanged (with space).

I also tried using Replace() replacing only space, but it didn’t work:

var newJson = json.Replace(" ", "");

I auditioned for Ideone: https://ideone.com/W6rAqE

inserir a descrição da imagem aqui

I copied EXACTLY the Original JSON and a strange character appeared in place of space. I could not identify anything. How to solve?

  • Here is working https://ideone.com/ddaSu6.

  • I copied the String straight from the original JSON and ran a test on Ideone. The funny thing that there instead of being showing an empty space, is a "point" highlighted. Is that some kind of break? https://ideone.com/W6rAqE

  • Because it does not use the var newJson = json.Replace(" ", "");?

  • Cypher, see the example here that I set up - https://ideone.com/W6rAqE for some reason some strange special character that I can’t identify. Ali is not really containing space...

1 answer

2


The character you are trying to replace is not a space, but a hard space (non-breaking space).

So just replace your Unicode code ( u00A0):

var newJson = json.Replace(":\"\u00A0", ":\"");

To find the decimal value of the character, just convert it:

Console.WriteLine((int)(' '));

The result is 160, which represents the hard space in the ASCII table.

You will also be able to remove this space using Regex:

Regex.Replace(json, @"[:][""]\s+", ":\"");

Testing: https://ideone.com/TweHsH

  • Thank you so much for the answer in detail friend, perfect solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.