Joao Castanheira
Joao Castanheira

Reputation: 45

JSON string format to URL Encode c#

I have a string JSON based in c#, with simple and complex objects, like this one:

{
"simple1": "xxx",
"simple2": "xxx",
"complex": {
    "complex_a": [{
        "complex_a_1_1": "aa",
        "complex_a_1_2": "aa"
    }, {
        "complex_a_2_1": 308,
        "complex_a_2_2": "select_option"
    }],
    "complex_b": [{
        "complex_b_1": "aa",
        "complex_b_2": "bb"
    }]
  }
}

And now i want to convert it to url encoded, like this:

string urlEncoded = "simple1=xxx&simple2=xxx&complex=%7Bcomplex_a=%5B%7Bcomplex_a_1_1=aa(...)%7B%5B%"

I've tried

HttpUtility.UrlEncode(JsonConvert.SerializeObject(myJsonString))

But it encode the json based charecters.

Anyone knows how to do it?

Upvotes: 2

Views: 14254

Answers (1)

El Duderino
El Duderino

Reputation: 1392

It's probably that you're serializing the JSON instead of deserializing it. Here is an example of how to load a JSON file and encode it in .Net Core.

string json;
using (var r = File.OpenText(@".\contents.json")) {
    json = r.ReadToEnd();
}

var data = JsonConvert.DeserializeObject(json);

var encoded = WebUtility.HtmlEncode(data);

JSON is already serialized. Serializing means to turn an object into a string. Since it's already a string, it's already serialized.

You need to deserialize it into an object and then URL encode it.

Upvotes: 1

Related Questions