从文件和显示中读取Json

时间:2015-10-25 21:22:59

标签: c# android json xamarin

我正在编写Android应用程序并拥有API

将API写入这样的文件

写作代码:

string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);

string path =  System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.Write(json.ToString());
    streamWriter.Close();
}

ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);

}
private async Task<JsonValue> FetchAsync(string url)
{
    // Create an HTTP web request using the URL:
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.ContentType = "application/json";
    request.Method = "GET";

    // Send the request to the server and wait for the response:
    using (WebResponse response = await request.GetResponseAsync())
    {
        // Get a stream representation of the HTTP web response:
        using (Stream stream = response.GetResponseStream())
        {
            // Use this stream to build a JSON document object:
            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
            //dynamic data = JObject.Parse(jsonDoc[15].ToString);
            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());

            // Return the JSON document:
            return jsonDoc;
        }
    }
}

我需要从文件中读取一些字段

我尝试这样做,但它没有工作

代码:

private void ParseAndDisplay1(JsonValue json)
{

    TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
    TextView price = FindViewById<TextView> (Resource.Id.price);
    TextView weight = FindViewById<TextView> (Resource.Id.weight);
    productname.Click += delegate {
        var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
        StartActivity (intent404);
    };
    string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
    string filename = System.IO.Path.Combine (path, "myfile.txt");

    using (var streamReader = new StreamReader (filename, true)) {
        JsonValue firstitem = json [81];

        productname.Text = firstitem ["post_title"];
        price.Text = firstitem ["price"] + " грн";
        weight.Text = firstitem ["weight"] + "г";
    }

}

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是一种简单的方法来阅读JSON并使用Json.NET进行操作,您可以从Xamarin安装:

var url = "http://new.murakami.ua/?mkapi=getProducts";
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

// Since you're just downloading the json you can use a webclient
using (var wc = new WebClient())
{
    // Download the json data
    var jsonData = await wc.DownloadStringTaskAsync(new Uri(url));

    // Save the json data
    File.WriteAllText(Path.Combine(path, "myfile.txt"), jsonData);

    // Deserialize the Json into a list of object of the type YourObject
    List<YourObject> list = JsonConvert.DeserializeObject<List<YourObject>>(jsonData);

    // Do whatever you want to do with the data
    foreach (var yourObject in list)
    {
        // this is just an example
        Console.WriteLine(yourObject.post_title);
    }
}

这是YourObject类的定义:

// this will hold the deserialized objects and make it easy to use
// You can delete properties you don't need
public class YourObject
{
    public int ID { get; set; }
    public string post_author { get; set; }
    public string post_date { get; set; }
    public string post_date_gmt { get; set; }
    public string post_content { get; set; }
    public string post_title { get; set; }
    public string post_excerpt { get; set; }
    public string post_status { get; set; }
    public string comment_status { get; set; }
    public string ping_status { get; set; }
    public string post_password { get; set; }
    public string post_name { get; set; }
    public string to_ping { get; set; }
    public string pinged { get; set; }
    public string post_modified { get; set; }
    public string post_modified_gmt { get; set; }
    public string post_content_filtered { get; set; }
    public int post_parent { get; set; }
    public string guid { get; set; }
    public int menu_order { get; set; }
    public string post_type { get; set; }
    public string post_mime_type { get; set; }
    public string comment_count { get; set; }
    public string filter { get; set; }
    public object img_url { get; set; }
    public string visibility { get; set; }
    public string price { get; set; }
    public string weight { get; set; }
    public string energy { get; set; }
    public string sku { get; set; }
    public int category { get; set; }
}