Xamarin Android deserializes local json file

I have a working JSON deserializer, but a JSON file with a url. How can I recreate this and make it work with a local JSON file? The file is at the root of my application, next to my MainActivity.

This is the working URL code:

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

    }
}
+4
source share
2 answers

I got his job. If I put my .json file in the Assets folder, install the Build Action on AndroidAsset and use the following code:

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);
    }
}
+6
source
var response = File.ReadAllText("myfile.json");

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

Source: https://habr.com/ru/post/1530414/


All Articles