2

I just can't figure this one out. Tried already with JsonConvert.SerializeObject(item) and I got a weird string as well.

How can I put out of value out of this stringified string?

"{\"value\":[\"18\"]}"

Edit@

This is where I stringify it:

    var data = new FormData();
    data.append('cates', JSON.stringify(toSend));

and here is what output I get from model > props list

https://gyazo.com/b9a6f212345b854796af3d80e4169a23

@deserializing

        foreach (var item in data.cates)
        {
            var l = JsonConvert.DeserializeObject(item);
        }
bunakawaka
  • 535
  • 6
  • 14
  • why does your json have the \" character?. What happens if you replace that string before deserializing?. Try removing that from the string – NicoRiff Jan 04 '17 at 01:06
  • 1
    You're going to need to supply more context. Where are you seeing that string? In a file? In C# source code? In the Visual Studio debugger? – Dour High Arch Jan 04 '17 at 01:07
  • The escaping is because the JSON String is in a String. Therefore the quotes have to be escaped – Timo Schwarzer Jan 04 '17 at 01:08
  • @DourHighArch edited – bunakawaka Jan 04 '17 at 01:09
  • 1
    Please show us the code you're actually using to deserialize it. You've only shown us how you're serializing it (however, you missed the important part of showing us what `toSend` it). Your attempt `JsonConvert.SerializeObject(item)` should be *Deserialize*, not *Serialize* – Rob Jan 04 '17 at 01:15
  • @Rob Done, sorry I missed that – bunakawaka Jan 04 '17 at 01:18
  • Wait, are you seeing that string in the Visual Studio debugger? [The debugger shows metacharacters escaped with backslashes](http://stackoverflow.com/a/39428787/22437); the backslashes and quotes are not part of the string. Please clarify. – Dour High Arch Jan 04 '17 at 01:45

1 Answers1

6

It looks as though your JSON has been double-serialized, i.e. an object was serialized to JSON, then that string was serialized again. See JSON.NET Parser seems to be double serializing my objects for an example of how this mistake can easily be made with asp.net-web-api.

The best way to solve the problem is to not double-serialize the JSON to begin with. If for whatever reason this cannot be fixed (because e.g. the double-serialized JSON is returned from some 3rd party service you cannot modify) you can always deserialize twice as well:

var json = @"""{\""value\"":[\""18\""]}""";

Console.WriteLine("JSON: ");
Console.WriteLine(json); // Prints "{\"value\":[\"18\"]}"

var intermediateJson = JsonConvert.DeserializeObject<string>(json);
var root = JsonConvert.DeserializeObject<RootObject>(intermediateJson);

Console.WriteLine("Reserialized root: ");
Console.WriteLine(JsonConvert.SerializeObject(root)); // Prints {"value":["18"]}
Console.WriteLine("value:");
Console.WriteLine(root.value.First()); // Prints 18

Using, for a root object:

public class RootObject
{
    public List<string> value { get; set; }
}
dbc
  • 104,963
  • 20
  • 228
  • 340