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 ?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.