将API写入文件

本文关键字:文件 API | 更新日期: 2023-09-27 18:18:16

你好,我是android开发的初学者

我在c#上用xamarin写android应用。我有产品列表活动

从API解析产品

的例子:

Array
(
    [0] => WP_Post Object
        (
            [ID] => 4538
            [post_author] => 7
            [post_date] => 2015-10-11 21:42:27
            [post_date_gmt] => 2015-10-11 17:42:27
            [post_content] => 
            [post_title] => Рол Філадельфія з лососем
            [post_excerpt] => Рис, Лосось, Норі, Сир Філадельфія, Авокадо, Ікра масаго
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => rol-filadelfiya-z-lososem
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-12 10:41:11
            [post_modified_gmt] => 2015-10-12 06:41:11
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/rol-filadelfiya-z-lososem/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Rol-Filadelfiya-z-lososem1.jpg
            [visibility] => visible
            [price] => 106.00
            [weight] => 215
            [energy] => 0
            [sku] => 423
            [category] => 87
        )
    [1] => WP_Post Object
        (
            [ID] => 4533
            [post_author] => 4
            [post_date] => 2015-10-09 17:32:51
            [post_date_gmt] => 2015-10-09 13:32:51
            [post_content] => 
            [post_title] => Васабі
            [post_excerpt] => на 1 сушку 2гр; на 1 ролл 4 гр; на набор
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => vasabi
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-11 22:22:19
            [post_modified_gmt] => 2015-10-11 18:22:19
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/vasabi/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/Vasabi.jpg
            [visibility] => visible
            [price] => 7.00
            [weight] => 4
            [energy] => 
            [sku] => 822
            [category] => 90
        )
    [2] => WP_Post Object
        (
            [ID] => 4378
            [post_author] => 4
            [post_date] => 2015-10-01 12:47:54
            [post_date_gmt] => 2015-10-01 08:47:54
            [post_content] => 
            [post_title] => Ямато
            [post_excerpt] => Курячий бульйон з яйцем / салат овочевий з заправкою насу / крохмальна локшина з овочами та свининою
            [post_status] => publish
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => yamato-0
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2015-10-08 14:38:18
            [post_modified_gmt] => 2015-10-08 10:38:18
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://new.murakami.ua/shop/yamato-0/
            [menu_order] => 0
            [post_type] => product
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
            [img_url] => http://new.murakami.ua/wp-content/uploads/YAmato.jpg
            [visibility] => visible
            [price] => 99.00
            [weight] => 225/110/175
            [energy] => 
            [sku] => 172
            [category] => 182
        )

当从URL激活活动时我解析它。

代码:

 string url2 = "http://new.murakami.ua/?mkapi=getProducts";
        JsonValue json = await FetchAsync(url2);
        ParseAndDisplay1(json);
        ParseAndDisplay2(json);
        ParseAndDisplay3(json);
        ParseAndDisplay4(json);
        ParseAndDisplay5(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)
    {

        //ImageButton product = FindViewById<ImageButton>(Resource.Id.vugor);
        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 intent485 = new Intent(this, typeof(GoryachieZakuskiDetailActivity1));
            StartActivity(intent485);
        };
        JsonValue firstitem = json[10];
        //Console.Out.WriteLine(firstitem["post_title"].ToString());
        productname.Text = firstitem["post_title"];
        price.Text = firstitem["price"] + " грн";
        weight.Text = firstitem["weight"] + "г";

    }

我想解析它一次到文本文件。并从文件中获取信息。

我该怎么做?

将API写入文件

@CDrosos的建议应该奏效,我只说一点:-)

此外,还可以使用file将文本字符串持久化到file中。WriteAllText(在内部使用StreamWriter),但使用起来简单得多:

bool SaveJson(string json)
{
   var documentFolder = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); 
   var fileNamePath = Path.Combine (documentFolder, "Products.json");
   File.WriteAllText(fileNamePath, json);
   return File.Exists(fileNamePath);
}

你当然可以使这个方法更通用,以便允许传递文件名和默认文件夹路径等。它可以被其他类使用。允许你的代码相当DRY(不要重复你自己的原则):

bool SaveText(string json, string fileName, string folderPath)
{
var fileNamePath = Path.Combine (folderPath, filename);
File.WriteAllText(fileNamePath, json);
return File.Exists(fileNamePath);
}

和SaveJson可以重构为:

bool SaveJson(string json)
{
    return SaveText
           (
              json
              , "Products.json"
              , Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)
           );
}

写入和读取文件非常容易:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
     streamWriter.WriteLine(DateTime.UtcNow);
}
using (var streamReader = new StreamReader(filename))
{
     string content = streamReader.ReadToEnd();
     System.Diagnostics.Debug.WriteLine(content);
}