将API写入文件

时间:2015-10-18 15:05:17

标签: c# android json api xamarin

你好我是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"] + "г";


    }

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

我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

@CDrosos建议应该起作用,有一点来自我: - )

此外,您还可以使用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);
}

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

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

答案 1 :(得分:2)

编写和阅读文件非常简单:

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