Mitch
Mitch

Reputation: 62

Characters not escaped properly when passing to dictionary

Before this is marked as a duplicate, the other question with a similar name is pertinent to regex and is different from my problem.

I have the string

Principal = "{\"id\":\"number\"}"

If I am not mistaken this should escape to {"id":"number"}.

However, when I pass it to the following method

Dictionary<string, object> folder = new Dictionary<string, object>();
            folder.Add("Principal", Principal);
            string json = JsonConvert.SerializeObject(folder);
            Console.WriteLine(json);

It returns as

{
"Principal":"{\"id\":\"number\"}"
}

Ideally I would like it to return

{
"Principal":{"id":"number"}
}

Why is it holding on to the quotes and escape characters? What am I doing wrong here?

Upvotes: 2

Views: 600

Answers (2)

dbc
dbc

Reputation: 116980

One option to add to @Compufreak's answer.

Your call to JsonConvert.SerializeObject() indicates you are already using . If you have a pre-serialized JSON literal string that you need to include as-is without escaping in some container POCO when the container is serialized, you can wrap the string in a JRaw object:

 folder.Add("Principal", new Newtonsoft.Json.Linq.JRaw(Principal));

JsonConvert.SerializeObject() will subsequently emit the JSON string without escaping. Of course, the Principal string needs to be valid JSON, otherwise the resulting serialization will be bad.

Sample fiddle.

Upvotes: 3

Vivien Sonntag
Vivien Sonntag

Reputation: 4639

Your Principal is a string, and so gets escaped as one.

If you want to escape it as an JSON object, it needs to be an object in your application as well.

If you also want to deserialize it or use it more than once, I propose to define your object in a class. If not, you can just use an anonymous object :

Dictionary<string, object> folder = new Dictionary<string, object>();
folder.Add("Principal", new { id = "number" });
string json = JsonConvert.SerializeObject(folder);
Console.WriteLine(json);

/edit: And here is it with a non-anonymous class:

Class definition:

class Principal
{
    public string id { get; set; }
}

Usage:

Dictionary<string, object> folder = new Dictionary<string, object>();
folder.Add("Principal", new Principal(){ id = "number" });
string json = JsonConvert.SerializeObject(folder);
Console.WriteLine(json);

Upvotes: 6

Related Questions