【问题标题】:Xamarin Android deserialize local json fileXamarin Android反序列化本地json文件
【发布时间】:2026-02-09 02:25:01
【问题描述】:

我有一个可用的 JSON 反序列化器,但它是来自 URL 的 JSON 文件。如何重新创建它并使其与本地 JSON 文件一起使用?该文件位于我的应用程序的根目录中,在我的 MainActivity 旁边。

这是来自 URL 的工作代码:

var client = new WebClient();
var response = client.DownloadString(new Uri("http://www.mywebsite.nl/form.json"));

List<Question> questions = JsonConvert.DeserializeObject<List<Question>>(response);

foreach(Question question in questions)
{

    if (question.type == "textField") {

        var editText  = new EditText (this);
        editText.Text = "This is question: " + question.id + ".";
        editText.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,ViewGroup.LayoutParams.WrapContent);
        layout.AddView (editText);

    }
}

【问题讨论】:

    标签: c# android json xamarin.android xamarin


    【解决方案1】:

    我得到了它的工作.. 必须将我的 .json 文件放在 Assets 文件夹中,将 Build Action 设置为 AndroidAsset 并使用下一个代码:

    string response;
    
    StreamReader strm = new StreamReader (Assets.Open ("form.json"));
    response = strm.ReadToEnd ();
    
    List<Vraag> vragen = JsonConvert.DeserializeObject<List<Vraag>>(response);
    
    foreach(Vraag vraag in vragen)
    {
        if (vraag.type == "textField") {
            var editText  = new EditText (this);
            editText.Text = "Dit is vraag: " + vraag.id + ".";
            editText.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,ViewGroup.LayoutParams.WrapContent);
            layout.AddView (editText);
        }
    }
    

    【讨论】:

      【解决方案2】:
      var response = File.ReadAllText("myfile.json");
      
      List<Question> questions = JsonConvert.DeserializeObject<List<Question>>(response);
      

      【讨论】:

      • 您的文件是否作为内容包含在您的应用程序包中?我知道这段代码适用于 Xamarin.iOS,我假设它也适用于 Xamarin.Android
      • 是的,它被标记为内容。我的总代码块是这样的:pastebin.com/z4y3ZASr
      最近更新 更多