Xamarin Forms IOS - NSData from a json string



我正在尝试从json字符串中获取NSData,以便稍后使用它来创建MGLShape(来自Mapbox SDK(,如下所示:

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.

但是我无法使用 NSJsonSerialization 将 json 字符串序列化为 NSData,json 字符串之前已更正和验证,(但是当我从字符串中使用 NSString 时,它会添加一对额外的括号"{//json }",我可以在尝试 NSJsonSerialization 之前将其删除,这是我尝试实现目标的方式:

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);

但它给了我以下错误:

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

是否使用额外的括号(从 NSString 中删除了第一个和最后一个字符(,都会发生此错误,这是我的 json 的缩短版本:(我用 https://jsonformatter.curiousconcept.com/来测试JSON(

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

我在这里做错了什么? 如何将 JSON 字符串解析为 NSData?

找到了一个超级简单的解决方案:

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

最新更新