1

I'm trying to write a C# class for a RESTful web service which returns some items but uses JSON Pagination. I'm using JSON.net for serialization and deserialization. I have the following code:

        static void RefTest()
        {
            PageTest PageToTest = new PageTest();
            PageToTest.next = new PageTest.PageLink();
            PageToTest.next.reference = "https://www.example.com/RESTQuery/?page=1";
            PageToTest.items = new List<string>();
            PageToTest.items.Add("Car");
            PageToTest.items.Add("Truck");
            PageToTest.items.Add("Plane");
            string JSON = JsonConvert.SerializeObject(PageToTest);
            PageTest DeserializedPageTest = JsonConvert.DeserializeObject<PageTest>(JSON);
        }

While the class looks as follows:

        public class PageTest
        {
            public PageLink next;
            public List<string> items;
            public class PageLink
            {
                [JsonProperty("$ref")]
                public string reference;
            }
        }

When I serialize that to a string, I get the expected result:

{
    "next": {
            "$ref":"https://www.example.com/RESTQuery/?page=1"
            },
    "items":
            [
            "Car",
            "Truck",
            "Plane"
            ]
}

Until now, everything works fine, it looks like json.net doesn't do anything special with the $ref property when serializing to a string.

Upon parsing of the string, however, json.net recognized the property named "$ref" as an reference to some id (which it can't find) and does NOT put it back on the deserialized object.

This is to be expected, but the web service is handing out pagination that way (With "next", "previous" and "last" attributes).

Basically, since it's impractical (I guess?) for the server to just give me all the values I will have to live with the pagination. So when I want to get all the items, I will have to deserialize the JSON response, check for additional items (indicated when there is a "next" property) and do the process again, until I have retrieved all the data I want.

Do you have any ideas on how I could handle that?

Thanks!

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
GeorgDangl
  • 2,146
  • 1
  • 29
  • 37
  • 1
    See [this similar question](http://stackoverflow.com/q/20686336/10263). You can use a custom JsonConverter to retrieve the `$ref` value and place it on your object. – Brian Rogers Nov 13 '14 at 17:34

0 Answers0