Search code examples
c#iosjsonxamarin.formsobservablecollection

Xamarin Forms - Observable Collection to CUSTOM JSON


I have an observable collection that contains a list of products that is binded to ListView.

However I want to export this Observable Collection as a JSON file AND only specific entries so I can submit it through the API.

For example.

The full observable collection contains

  • Product ID
  • Product Name
  • Product Price
  • Product Qty

But I want to extract the JSON file to only:

  • Product ID
  • Product Qty

Here's my code:

public static ObservableCollection<FBProduct> fbproducts = new ObservableCollection<FBProduct>();

Here's my JSON deserialiser

shoppingcartjson = JsonConvert.SerializeObject(ShoppingCart.fbproducts);

How can I only extract only ProductID and ProductQTY from that ObservableCollection like so:

"line_items": [{"product_id":79631,"quantity":1}],

Solution

  • It's simple in your FBProduct class use the JsonIgnore attribute!

    For instance:

     public class FBProduct
     {    
        [JsonIgnore]
        public double Name  { get; set; } 
        .
        .
    

    Also, add the following using statement:

    using Newtonsoft.Json;
    

    Good luck!

    Feel free to get back if you have questions.