2

I have an object with private field that contains collection of POCOs. I want to be able to serialize it using the Newtonsoft.Json portable package. What is the appropriate way? In other words what should be the implementation of the contract resolver? Thanks.

Needs to be portable, so using binding flags isn't an option, unless a shim library is introduced.

As to concrete example, think of something like this:

[Serializable]
public class SimpleItemDto
{
    public string Name { get; set; }
    public double Price { get; set; }
    public int Quantity { get; set; }
}

public interface ISimpleProvider
{
    IEnumerable<SimpleItemDto> GetSimpleItems();
}    

[Serializable]
class SimpleProviderBuilder : FakeBuilderBase<ISimpleProvider>
{
    private readonly List<SimpleItemDto> _warehouseItemsStorage = new List<SimpleItemDto>();

    private SimpleProviderBuilder()
    {

    }

    public static SimpleProviderBuilder CreateBuilder()
    {
        return new SimpleProviderBuilder();
    }

    public void WithWarehouseItems(IEnumerable<SimpleItemDto> warehouseItems)
    {
        _warehouseItemsStorage.Clear();
        _warehouseItemsStorage.AddRange(warehouseItems);
    }       

    protected override IServiceCall<ISimpleProvider> CreateServiceCall(IHaveNoMethods<ISimpleProvider> serviceCallTemplate)
    {
        var setup = serviceCallTemplate
           .AddMethodCallWithResult(t => t.GetSimpleItems(), r => r.Complete(GetSimpleItems));
        return setup;
    }

    private IEnumerable<SimpleItemDto> GetSimpleItems()
    {
        return _warehouseItemsStorage;
    }
}

Pay attention that the DTOs might get complex as well so the serialization has to be hierarchical.

dbc
  • 104,963
  • 20
  • 228
  • 340
Gena Verdel
  • 588
  • 5
  • 21
  • Is this what you want: [Json.net serialize specific private field](https://stackoverflow.com/questions/32008869) ? Or this: [JSON.Net: Force serialization of all private fields and all fields in sub-classes](https://stackoverflow.com/questions/24106986) ? If neither are what you need, can you give a [concrete example](https://stackoverflow.com/help/mcve) of what you want and why those answers don't meet your needs? – dbc May 28 '16 at 22:38
  • The solution has to be portable so use of binding flags is not an option. Edited the question. – Gena Verdel May 29 '16 at 06:32

0 Answers0