3

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

Hunt
  • 8,215
  • 28
  • 116
  • 256

2 Answers2

3

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.-

pinedax
  • 9,246
  • 2
  • 23
  • 30
  • All i am trying to pass the json string into `requset.Body` and `request.Body` does take `NSData` as an argument hence i used `NSJsonSerialization` but the problem is `NSJsonSerialization` does access its first argument as `NSObject` so how can i convert my `{"password":"Abc134","companyId":"CM1","userName":"450012"}` to NSObject os that `NSJsonSerialization` can accept it – Hunt Mar 04 '19 at 11:49
0

Yes, you can try to create a custom object to serialize. Create a simple plain object to hold the data you want.

User user = new User() {
    UserName = "JohnDoe",
    Password = "xxx",
    CompanyId = 01
};
request.Body = NSJsonSerialization.Serialize(user, 0, out error);

Then serialize it and you will see the proper json well formed.

SergioAMG
  • 428
  • 2
  • 10