Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Android deserialize local json file

I got a working JSON deserializer but that's a JSON file from an URL. How can I recreate this and make it work with a local JSON file? The file is in the Root of my application, next to my MainActivity.

This is the working code from the 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);

    }
}
like image 326
Tom Spee Avatar asked Mar 06 '14 12:03

Tom Spee


2 Answers

I got it working.. Had to put my .json file in the Assets folder, set the Build Action to AndroidAsset and use the next 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);
    }
}
like image 68
Tom Spee Avatar answered Nov 14 '22 23:11

Tom Spee


var response = File.ReadAllText("myfile.json");

List<Question> questions = JsonConvert.DeserializeObject<List<Question>>(response);
like image 34
Jason Avatar answered Nov 14 '22 23:11

Jason