Xamarin Forms IOS - NSData from a json string

RicardoPORRicardoPOR Member ✭✭
edited June 7 in Xamarin.Forms

I'm trying to get an NSData from a json string, to use it later to create an MGLShape (From Mapbox SDK) like this:

MGLShape.ShapeWithData(jsonData, 4, out error); //jsonData is the NSData, 4 is the nuint for the type of encoding and ou error is a plain NSError.

But i'm not able to serialize the json string into NSData using NSJsonSerialization, the json string is corrected and validated before, (but when i use an NSString from the string, it adds an extra pair of brackets "{ //json }", which i can remove before trying the NSJsonSerialization, here is how i'm trying to achive my goal:

string jsonSerialized = JsonConvert.SerializeObject(fc);//Valid Json
NSString json = new NSString(jsonSerialized);//Adds the extra pair of brackets
NSData jsonData = NSJsonSerialization.Serialize(json, NSJsonWritingOptions.SortedKeys, out error);

But it gives me the following error:

Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSInvalidArgumentException Reason: *** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write

This error happens with, or without the extra pair of brackets (removed the first and last chars from the NSString), here is a shortned version of my json:
(i used https://jsonformatter.curiousconcept.com/ to test the json)

{"type":"FeatureCollection","crs":null,"features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-9.000000,38.000000]},"properties":{"id":1,"icon":"MyIcon.png"}}]}

What am i doing wrong here? how can i parse an json string into an NSData?

Best Answers

  • RicardoPORRicardoPOR ✭✭
    Accepted Answer

    I found a solution.. quite simple:

    NSData jsonData = NSData.FromString(jsonSerialized, NSStringEncoding.UTF8);
    

Answers

  • RicardoPORRicardoPOR Member ✭✭
    Accepted Answer

    I found a solution.. quite simple:

    NSData jsonData = NSData.FromString(jsonSerialized, NSStringEncoding.UTF8);
    
  • RicardoPORRicardoPOR Member ✭✭

    @ColeX it worked too! but i found my solution to be more simple

  • ColeXColeX Member, Xamarin Team Xamurai

    @RicardoPOR said:
    @ColeX it worked too! but i found my solution to be more simple

    Of course ,your solution is the direct method from NSString to NSData.

  • RicardoPORRicardoPOR Member ✭✭

    @ColeX said:

    @RicardoPOR said:
    @ColeX it worked too! but i found my solution to be more simple

    Of course ,your solution is the direct method from NSString to NSData.

    i was overcomplicating things up, thank you anyway for your time

Sign In or Register to comment.