Rabia
Rabia

Reputation: 47

How to create JSON from C# dictionary similar to PHP

PHP code to make an array

$tag = array(
'tag_uid' => 1234,
'x' => 0,
'y' => 0
);

$tags[] = $tag;

OUTPUT: {"x":"0","y":"0","tag_uid":"1234"}

I want to make this as JSON array in C# with the same OUTPUT for that I need help, I can't figure out which array it will be? a simple array or what. I have tag_uid which i can pass to function and i am using JSON.NET I don't know what should i need to write in the JsonArry function but I have tried to following

 public JsonArray CreatePhotoTag(string userId)
        {
            Dictionary<string, object> tagParameters = new Dictionary<string, object>();
            tagParameters.Add("x", "0");
            tagParameters.Add("y", "0");
            tagParameters.Add("tag_uid", userId);
            JsonArray tagsarray = ???

            return tagsarray ;
        }

Please help me

Upvotes: 2

Views: 1026

Answers (1)

Andrew T Finnell
Andrew T Finnell

Reputation: 13638

I recommend switching to ServiceStack.NET Text. It is incredibly fast compared to JSON.NET.

You can serialize it like this:

ServiceStack.NET

var jsonSerializer = new JsonSerializer<Dictionary<String, Object>>();
var tagsArray = jsonSerializer.SerializeToString(tagParameters);

If you really want to use JSON.NET

JSON.NET

var tagsArray = JsonConvert.SerializeObject(tagParameters, Formatting.Indented);

Upvotes: 3

Related Questions