4

I want to do a JSON get request on a REST API.
When I post a resource and use a get immediately after that I get a JSON object in my response.
When I put the resource after I post and use a get after that then the JSON object changes into an array.
Here are some example responses I get:

After post and put :

{  
    "metadata":{  
      "entry":[  
         {  
            "@key":"x",
            "$":"y"
         },
         {  
            "@key":"x",
            "$":"y"
         }
      ]
    }
}

After only post :

{
"metadata": {
        "entry": {
            "@key": "cachingEnabled",
            "$": "false"
        }
    },
}

I can get it both working using the either of the following code.

JSON array :

public class MetaData
{
    [JsonProperty("entry")]       
    public List<EntryType> Entry { get; set; }
}

JSON object :

public class MetaData
{
    [JsonProperty("entry")]       
    public EntryType Entry { get; set; }
}

How can I map this in c# to one property ?

DannyBiezen
  • 117
  • 5
  • 1
    Define the property as a `List` then use a JsonConverter to detect the single instance and put it into the list. See [How to handle both a single item and an array for the same property using JSON.net](http://stackoverflow.com/q/18994685/10263) - the accepted answer has a generic converter already written that should work for you. – Brian Rogers Sep 29 '14 at 17:15

1 Answers1

0

You can map it to a dynamic type, which lets the compiler defer the type at run-time:

public class MetaData
{
    [JsonProperty("entry")]       
    public dynamic Entry { get; set; }
} 

That way, each time you deserialize Entry it may be of a different type. You'll have to keep track which type it is after you deserialize your JSON.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321