Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary to Json in Xamarin.iOS

I am trying to convert the NSDictionary into Json using NSJsonSerialization.Serialize. But i am not getting expected output

Code in Xamarin.iOS

var dictionary = new NSDictionary(
                new NSString("userName"), new NSString("450012"),
                new NSString("password"), new NSString("Abc134"),
                new NSString("companyId"), new NSString("CM1")
            );

request.Body = NSJsonSerialization.Serialize(dictionary, 0, out error); 

the problem is that value of dictionary variable is showing

{{password":Abc134,companyId:CM1,userName:450012}}

instead of

{password:Abc134,companyId:CM1,userName:450012}

it is adding one curly braces at the front and back

is there any way to generate proper json string for user input values

like image 839
Hunt Avatar asked Feb 04 '26 08:02

Hunt


1 Answers

There's nothing wrong with your json. If you print it in the console you will see that the value being printed is the value you expect.

{"password":"Abc134","companyId":"CM1","userName":"450012"}

Give it a try with:

Console.WriteLine($"{json}");

If you really, really want to get rid of of that "extra" curly braces just convert the result into string.

var jsonString = json.ToString();

The above should do the work.

I would just suggest you changing your method to this: var json2 = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);

Using the PrettyPrinted option.

Hope this helps.-

like image 140
pinedax Avatar answered Feb 15 '26 12:02

pinedax