【发布时间】:2022-01-14 02:23:47
【问题描述】:
我有一个矢量 json 文件,其中包含每个用户的特定数据(一些记录是同一用户的一部分),我想读取它并在字典中反序列化它(我必须从文件中插入键和值)
【问题讨论】:
-
如果您提供您正在使用的 json 样本以及您想要反序列化的数据结构,这将非常有帮助。
标签: json dictionary xamarin.forms
我有一个矢量 json 文件,其中包含每个用户的特定数据(一些记录是同一用户的一部分),我想读取它并在字典中反序列化它(我必须从文件中插入键和值)
【问题讨论】:
标签: json dictionary xamarin.forms
假设这里是json数据
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
将 json 文件添加到您的共享项目中,并将其 Build Action 设置为 Embedded resource。
使用json2csharp生成模型类。
public class GlossDef
{
public string para { get; set; }
public List<string> GlossSeeAlso { get; set; }
}
public class GlossEntry
{
public string ID { get; set; }
public string SortAs { get; set; }
public string GlossTerm { get; set; }
public string Acronym { get; set; }
public string Abbrev { get; set; }
public GlossDef GlossDef { get; set; }
public string GlossSee { get; set; }
}
public class GlossList
{
public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
public string title { get; set; }
public GlossList GlossList { get; set; }
}
public class Glossary
{
public string title { get; set; }
public GlossDiv GlossDiv { get; set; }
}
public class Root
{
public Glossary glossary { get; set; }
}
使用Newtonsoft.Json将json反序列化为object。
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(App)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourNameSpace.test.json");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
}
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(text);
【讨论】: