Reputation: 2508
I am dealing with an API that returns something like this:
{"v1.ProjectList":
{
"self_link": { "href": "https://central-staged:8880/api/v1/projects", "methods": "GET" },
"items": [],
"register": {"href": "https://central-staged:8880/api/v1/projects/register", "methods": "POST"},
"max_active": {"href": "https://central-staged:8880/api/v1/projects/max-active", "methods": "GET"}
}
}
I am generating a bunch of DTOs to accommodate the de-serialisation of of that JSON string.
namespace v1
{
public class Project
{
public rest_common.Link branches { get; set; }
public float coordinate_x { get; set; }
public float coordinate_y { get; set; }
public string description { get; set; }
public int id { get; set; }
public string location { get; set; }
public string name { get; set; }
public rest_common.Link publish_events { get; set; }
public rest_common.Link self_link { get; set; }
public rest_common.Link thumbnail { get; set; }
public System.Guid uuid { get; set; }
}
[JsonObject(Title = "v1.ProjectList")]
public class ProjectList
{
public List<Project> items { get; set; }
public rest_common.Link max_active { get; set; }
public rest_common.Link register { get; set; }
public rest_common.Link self_link { get; set; }
}
}
namespace rest_common
{
public class Link
{
public string href { get; set; }
public string methods { get; set; }
}
}
That code was generated from server-side code and I can modify it to suit. The only thing I cannot modify at this time is the JSON response returned by the server.
I am trying to figure out how to deserialise this:
class Program
{
static void Main(string[] args)
{
var jsonContent = "{\"v1.ProjectList\": {\"self_link\": {\"href\": \"https://something.com/getblah\", \"methods\": \"GET\"}, \"items\": [], \"register\": {\"href\": \"https://something.com/postblah\", \"methods\": \"POST\"}, \"max_active\": {\"href\": \"https://something.com/getblah2\", \"methods\": \"GET\"}}}";
var projectList = JsonConvert.DeserializeObject<ProjectList>(jsonContent);
Console.ReadLine();
}
}
At the moment projectList
is an instance of the correct class, but all its members are null
.
Upvotes: 0
Views: 117
Reputation: 418
Alternatively, since you are creating a new instance of the class you are deserializing the string of JSON from, indicate that:
var projectList = new (ProjectList)(JsonConvert.DeserializeObject<ProjectList>(jsonContent));
Upvotes: 0
Reputation: 18379
You are trying to deserialize an object that contains a single property named v1.ProjectList
. So create such class:
public class ProxyObject
{
[JsonPropertyAttribute("v1.ProjectList")]
public ProjectList ProjectList { get; set;}
}
.. And then this works:
var projectList = JsonConvert.DeserializeObject<ProxyObject>(jsonContent).ProjectList;
The attribute [JsonObject(Title = "v1.ProjectList")]
is unnecessary.
Upvotes: 2