简体   繁体   English

缓存JSON(Xamarin C#)

[英]Caching JSON (Xamarin C#)

I writing Android app and want professional advice. 我正在编写Android应用,需要专业建议。

I have category with products. 我的产品类别。

I have JSON with this products. 我的产品带有JSON。

    Array
(
    [0] => Array
        (
            [post_title] => Яблочный десерт
            [post_excerpt] => Мус топленный шоколад, яблоко в карамели с ореховым тестом.
            [img_url] => http://new.murakami.ua/wp-content/uploads/Untitled-1.jpg
            [visibility] => visible
            [price] => 78.00
            [weight] => 90
            [sku] => 594
        )

    [1] => Array
        (
            [post_title] => Сладкий ролл Филадельфия с клубникой и ананасом
            [post_excerpt] => 
            [img_url] => http://new.murakami.ua/wp-content/uploads/roll_sladkiy2.jpg
            [visibility] => visible
            [price] => 68.00
            [weight] => 100
            [sku] => 846
        )

    [2] => Array
        (
            [post_title] => Тирамису
            [post_excerpt] => Бисквит, сыр креметте, сливки, какао, кофе Lavazza, ликер Triple Sec Volare
            [img_url] => http://new.murakami.ua/wp-content/uploads/Tiramisu.jpg
            [visibility] => visible
            [price] => 59.00
            [weight] => 110
            [sku] => 248
        )

    [3] => Array
        (
            [post_title] => Наполеон   

            [post_excerpt] => Торт из слоёных коржей с заварным кремом.
            [img_url] => http://new.murakami.ua/wp-content/uploads/Napoleon.jpg
            [visibility] => visible
            [price] => 58.00
            [weight] => 140
            [sku] => 633
        )

    [4] => Array
        (
            [post_title] => Ассорти мини чизкейков
            [post_excerpt] => Чизкейк с ванильно-сырным муссом, с фисташковым муссом Баваруа и шоколадным крем-брюле, в основе которых ореховый чизкейк с миндального бисквита и крем-сыра Президент.
            [img_url] => http://new.murakami.ua/wp-content/uploads/535_520-Assorti-CHizkejkov.jpg
            [visibility] => visible
            [price] => 84.00
            [weight] => 130
            [sku] => 141
        )

    [5] => Array
        (
            [post_title] => Шоколадно-авокадовый десерт
            [post_excerpt] => Шоколадный бисквит, слой миндаля, шоколадный мусс с авокадо, сироп Амаретто, шоколад.
            [img_url] => http://new.murakami.ua/wp-content/uploads/SHokoladno-avokadovyj-desert.jpg
            [visibility] => visible
            [price] => 64.00
            [weight] => 100
            [sku] => 225
        )

)

I need to cache it and then show some of fields in UI. 我需要对其进行缓存,然后在UI中显示一些字段。

Now I Download it and show in UI,like this. 现在,我下载它并在UI中显示,就像这样。

Downloading: 正在下载:

    string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
            JsonValue json = await FetchAsync(url2);
 private async Task<JsonValue> FetchAsync(string url)
        {
            System.IO.Stream jsonStream;
            JsonValue jsonDoc;

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                jsonStream = await httpClient.GetStreamAsync(url);
                jsonDoc = JsonObject.Load(jsonStream);
            }

            return jsonDoc;
        }

And Displaying : 并显示:

 private void ParseAndDisplay(JsonValue json)
    {



        TextView productname = FindViewById<TextView>(Resource.Id.posttittle);
        TextView price = FindViewById<TextView>(Resource.Id.price);
        TextView weight = FindViewById<TextView>(Resource.Id.weight);
        ImageView imagen = FindViewById<ImageView>(Resource.Id.image1);
        ImageButton add = FindViewById<ImageButton> (Resource.Id.add);

        JsonValue firstitem = json[0];
        //Console.Out.WriteLine(firstitem["post_title"].ToString());

        productname.Text = firstitem["post_title"];
        price.Text = firstitem["price"] + " грн";
        weight.Text = firstitem["weight"] + "г";
        var imageBitmap = GetImageBitmapFromUrl(firstitem["img_url"]);
        imagen.SetImageBitmap(imageBitmap);


    }

How can I make a cache for this JSON and don't download this JSON each time , when user goes to product category? 当用户转到产品类别时,如何为该JSON缓存,而不每次都下载此JSON?

Thank's for help & advice. 感谢您的帮助和建议。

You can store a serialized json object as string into the preferences. 您可以将序列化的json对象作为字符串存储到首选项中。

The Xamarin.Android equivalent of SharedPreferences is an interface called ISharedPreferences . 与SharedPreferences等效的Xamarin.Android是一个称为ISharedPreferences的接口。

You'll want to get an instance of ISharedPreferences and use that to update/change/delete preferences. 您将需要获取ISharedPreferences的实例,并使用该实例来更新/更改/删除首选项。 There are a couple of ways to get an instance of ISharedPreferences: 有两种方法可以获取ISharedPreferences实例:

  • Activity.GetPreferences would get you preferences specific to that activity. Activity.GetPreferences将获得特定于该活动的首选项。 Probably not what you want. 可能不是您想要的。

  • Context.GetSharedPreferences can get you application level preferences. Context.GetSharedPreferences可以获取应用程序级别的首选项。

  • PreferenceManager.DefaultSharedPreferences will give you an ISharedPreference instance for a given context. PreferenceManager.DefaultSharedPreferences将为您提供给定上下文的ISharedPreference实例。

Use it in the same way, and you will be able to easily port Android code across. 以相同的方式使用它,您将能够轻松地移植Android代码。

For example, to save a string you can do the following: 例如,要保存字符串,您可以执行以下操作:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString(key, value);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs

To read the saved values you can do: 要读取保存的值,您可以执行以下操作:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mString = prefs.GetString(key, default_value_to_return_in_case_no_value_is_found);

Where key is of course the same previously used to store the string. 当然,其中的key与以前用于存储字符串的相同。 Once you have your mString you can deserialize it into any complex json object. 一旦有了mString,就可以将其反序列化为任何复杂的json对象。

You can also explore the other types of data that you can store (int, bool ...) 您还可以探索可以存储的其他类型的数据(int,bool ...)

Check here https://forums.xamarin.com/discussion/4758/android-shared-preference for more examples. 在此处查看https://forums.xamarin.com/discussion/4758/android-shared-preference以获取更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM