BirdsAreSpies
BirdsAreSpies

Reputation: 3

Serialize JSON propertly

I am trying to serialize a string array into JSON and I am using Newtonsoft JSON.Net for this but the output is wrong and I don't know how to serialize it properly.

I use this code:

string[] subscriptions = new string[] { "downloads" }; 
string[] exclusion = new string[] { "REFRESH_CONTENT" };
var toSend = new string[][] { subscriptions, exclusion };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(toSend);

And I get this result:

params: [[\"downloads\"],[\"REFRESH_CONTENT\"]]

But I need to get this result:

params: [\"[\\\"downloads\\\"]\",\"[\\\"REFRESH_CONTENT\\\"]\"]
or without escaped strings (to be sure there is no error in the line above):
params: ["[\"downloads\"]","[\"REFRESH_CONTENT\"]"]

Thanks!

Upvotes: 0

Views: 70

Answers (1)

derpirscher
derpirscher

Reputation: 17372

Your expectations are wrong. Your toSend is an array of string arrays. And this is what the serialization produces. If you want to get an array of strings, you have to create one:

var toSend = new string[] {JsonConvert.SerializeObject(subscriptions), JsonConvert.SerializeObject(exclusion)};
string json = JsonConvert.SerializeObject(toSend);

But this way, you'll have to parse each element of the array at the receiver side.

Upvotes: 2

Related Questions