【问题标题】:Writing API to file将 API 写入文件
【发布时间】:2016-01-16 22:04:59
【问题描述】:

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


    }

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

我该怎么做?

【问题讨论】:

    标签: c# android json api xamarin


    【解决方案1】:

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

    【讨论】:

      【解决方案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);
      }
      

      【讨论】:

      • 据我了解这一行 streamWriter.WriteLine(DateTime.UtcNow);写具体信息 我需要通过链接写下我拥有的所有文本 我该怎么做?
      • 用包含所有文本的变量替换 DateTime.UtcNow
      猜你喜欢
      • 2021-10-12
      • 2012-03-31
      • 2011-11-21
      • 2021-04-27
      • 1970-01-01
      • 2013-11-13
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多