Xamarin Forms IOS - 来自 json 字符串的 NSData
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);
我正在尝试从 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);