Reputation: 11
I try to deserialize a json-string into object with Newtonsoft.Json
. But JsonConvert.DeserializeObject()
always returns null.
string json2 = "[{ 'id':1,'date':'2016-05-10T03:48:21','date_gmt':'2016-05-10T03:48:21','guid':{ 'rendered':'http://test.de/?p=1'},'modified':'2019-02-27T11:56:21'}]";
List<Product> myProducts = new List<Product>();
myProducts = JsonConvert.DeserializeObject<List<Product>>(json2); // allways null!?
I guess the reason lies in the class MyGuid
. The setter of the property Rendered
is never reached.
I have read all questions about this theme here but didn't find the right answer to my question.
Here is the whole code example:
namespace JsonToObject
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
string json2 = "[{ 'id':1,'date':'2016-05-10T03:48:21','date_gmt':'2016-05-10T03:48:21','guid':{ 'rendered':'http://test.de/?p=1'},'modified':'2019-02-27T11:56:21'}]";
List<Product> myProducts = new List<Product>();
myProducts = JsonConvert.DeserializeObject<List<Product>>(json2); // allways null!
}
}
public class Product
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("date")]
public string Date { get; set; }
[JsonProperty("date_gmt")]
public string Date_gmt { get; set; }
[JsonProperty("guid")]
public MyGuid MyGuid { get; set; }
[JsonProperty("modified")]
public string Modified { get; set; }
}
public class MyGuid
{
[JsonProperty("rendered")]
public string Rendered { get; set; } // not reached!
}
}
Can anyone help me?
Upvotes: 1
Views: 1347
Reputation: 12723
But
JsonConvert.DeserializeObject()
always returns null.
Your code is no problem.Normally this return an json array object.
If you check myProducts
directly, then it is an array object, you need to specify which element in the array, which property can get Rendered
.
Since your json array contains only one object, getting Rendered can be written like this:
myProducts[0].MyGuid.Rendered
Then this will return :
http://test.de/?p=1
All parameters are get as follow:
myProducts//------ System.Collections.Generic.List`1[App1.Views.MainPage+Product]
myProducts[0].Id //------1
myProducts[0].Date//------2016-05-10T03:48:21
myProducts[0].Date_gmt//------2016-05-10T03:48:21
myProducts[0].Modified//------2019-02-27T11:56:21
myProducts[0].MyGuid.Rendered//------http://test.de/?p=1
If also has problem, you can share link of solution.I will check it.
Upvotes: -1