如何读取JSON文件内容并将其转写入Xamarin项目中
我已将该JSON文件导入项目中,如你所见,它是一个向量:
{ "objArray": [ { "min_position": 4, "has_more_items": false, "items_html": "Bike", "new_latent_count": 7 }, { "min_position": 9, "has_more_items": false, "items_html": "Car", "new_latent_count": 8 }, { "min_position": 9, "has_more_items": false, "items_html": "Bus", "new_latent_count": 8 }, { "min_position": 3, "has_more_items": true, "items_html": "Car", "new_latent_count": 1 }, { "min_position": 3, "has_more_items": false, "items_html": "Bus", "new_latent_count": 9 } ] }请问是否有方法可以完整读取该JSON的全部内容,并将其转写入Xamarin中?
可以实现,你可以按照以下步骤完成操作:
步骤1:定义匹配JSON结构的C#实体类
首先创建和JSON字段一一对应的强类型实体类,方便解析后直接操作数据,示例代码如下:
using System.Collections.Generic; // 使用System.Text.Json库用JsonPropertyName特性 using System.Text.Json.Serialization; // 如果使用Newtonsoft.Json库,替换为 using Newtonsoft.Json; // 数组子项对应的实体类 public class ArrayItem { [JsonPropertyName("min_position")] // Newtonsoft.Json用户替换为 [JsonProperty("min_position")] public int MinPosition { get; set; } [JsonPropertyName("has_more_items")] public bool HasMoreItems { get; set; } [JsonPropertyName("items_html")] public string ItemsHtml { get; set; } [JsonPropertyName("new_latent_count")] public int NewLatentCount { get; set; } } // JSON根对象对应的实体类 public class JsonRoot { [JsonPropertyName("objArray")] public List<ArrayItem> ObjArray { get; set; } }
步骤2:读取项目中的JSON文件
以最通用的嵌入资源读取方式为例:
- 右键项目中的JSON文件,选择「属性」,将「生成操作」设置为「嵌入的资源」
- 用以下代码读取文件内容为字符串:
using System.IO; using System.Reflection; var assembly = Assembly.GetExecutingAssembly(); // 替换下方的命名空间和文件名,格式为「你的项目命名空间.你的JSON文件名.json」 var resourcePath = "YourAppNamespace.data.json"; string jsonContent; using (Stream stream = assembly.GetManifestResourceStream(resourcePath)) using (StreamReader reader = new StreamReader(stream)) { jsonContent = reader.ReadToEnd(); }
如果你的JSON放在不同平台的专属资源目录下,按对应规则调整即可:
- 安卓Assets目录:生成操作设为
AndroidAsset,用Assets.Open("文件名.json")获取读取流 - iOS Resources目录:生成操作设为
BundleResource,用File.ReadAllText(NSBundle.MainBundle.PathForResource("文件名", "json"))直接读取内容
步骤3:解析JSON为强类型对象
System.Text.Json 解析示例:
using System.Text.Json; var jsonData = JsonSerializer.Deserialize<JsonRoot>(jsonContent);
Newtonsoft.Json 解析示例:
using Newtonsoft.Json; var jsonData = JsonConvert.DeserializeObject<JsonRoot>(jsonContent);
解析完成后的jsonData就包含了JSON文件的全部内容,你可以直接在Xamarin项目中使用这些数据,比如绑定到列表控件、存入本地数据库等。
内容的提问来源于stack exchange,提问作者user16937336
相关产品推荐
相关产品推荐

